Как заменить unsafeWindow при переносе скрипта Greasemonkey до Firefox 30 в GM4 +? - PullRequest
0 голосов
/ 08 мая 2018

Я пытаюсь получить ссылку на версию jQuery, которая существует на моей веб-странице в скрипте Greasemonkey, который работал до Firefox 30. В комментариях ниже моего определения есть две другие ссылки, которые я мог найти, но я просто получаю ReferenceError: $ is not defined или ReferenceError: jQuery is not defined, когда я пытаюсь получить доступ к jQuery для объекта окна.

var $ = unsafeWindow.jQuery;
//var jQuery = window.jQuery; // From https://stackoverflow.com/questions/24802606/binding-to-an-event-of-the-unsafewindow-in-firefox-30-with-greasemonkey-2-0
//var jQuery = $ || window.wrappedJSObject.$; // https://github.com/greasemonkey/greasemonkey/issues/2700#issuecomment-345538182
function addAccountNameToTitle(jNode) {
  $('title').text(session.name + " | " + $('title').text());
}

waitForKeyElements (".page-breadcrumb", addAccountNameToTitle, false);

/*--- waitForKeyElements():  A handy, utility function that
    does what it says.
*/
function waitForKeyElements (
    selectorTxt,    /* Required: The jQuery selector string that
                        specifies the desired element(s).
                    */
    actionFunction, /* Required: The code to run when elements are
                        found. It is passed a jNode to the matched
                        element.
                    */
    bWaitOnce,      /* Optional: If false, will continue to scan for
                        new elements even after the first match is
                        found.
                    */
    iframeSelector  /* Optional: If set, identifies the iframe to
                        search.
                    */
)
{
    var targetNodes, btargetsFound;

    if (typeof iframeSelector == "undefined")
        targetNodes     = $(selectorTxt);
    else
        targetNodes     = $(iframeSelector).contents ()
                                           .find (selectorTxt);

    if (targetNodes  &&  targetNodes.length > 0) {
        /*--- Found target node(s).  Go through each and act if they
            are new.
        */
        targetNodes.each ( function () {
            var jThis        = $(this);
            var alreadyFound = jThis.data ('alreadyFound')  ||  false;

            if (!alreadyFound) {
                //--- Call the payload function.
                actionFunction (jThis);
                jThis.data ('alreadyFound', true);
            }
        } );
        btargetsFound   = true;
    }
    else {
        btargetsFound   = false;
    }

    //--- Get the timer-control variable for this selector.
    var controlObj      = waitForKeyElements.controlObj  ||  {};
    var controlKey      = selectorTxt.replace (/[^\w]/g, "_");
    var timeControl     = controlObj [controlKey];

    //--- Now set or clear the timer as appropriate.
    if (btargetsFound  &&  bWaitOnce  &&  timeControl) {
        //--- The only condition where we need to clear the timer.
        clearInterval (timeControl);
        delete controlObj [controlKey]
    }
    else {
        //--- Set a timer, if needed.
        if ( ! timeControl) {
            timeControl = setInterval ( function () {
                    waitForKeyElements (    selectorTxt,
                                            actionFunction,
                                            bWaitOnce,
                                            iframeSelector
                                        );
                },
                500
            );
            controlObj [controlKey] = timeControl;
        }
    }
    waitForKeyElements.controlObj   = controlObj;
}

Я использую FF 59.0.2 и Greasemonkey 4.3

1 Ответ

0 голосов
/ 09 мая 2018

unsafeWindow.jQuery никогда не было хорошей идеей и редко работало. Также см. Ошибка: в доступе к свойству 'handler' отказано в доступе .

умный , что нужно сделать с кодом вопроса, это использовать @require, вот так:

// ==UserScript==
// @name     _Changing the title text on some page.
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// @grant    GM.getValue
// ==/UserScript==
//- The @grant directives are needed to restore the proper sandbox.

waitForKeyElements (".page-breadcrumb", addAccountNameToTitle);

function addAccountNameToTitle (jNode) {
    $('title').text (session.name + " | " + $('title').text() );
}

Преимущества:

  • Коротко, просто и понятно.
  • Не подвержен побочным эффектам от изменения JavaScript на целевой странице. Особенно, если целевая страница изменяет версии jQuery.
  • Использует быстрые локальные версии jQuery и waitForKeyElements. Они хранятся на локальном диске и часто кэшируются в памяти. Сервер не получает и не задерживает.

Примечание: если session является глобальной переменной целевой страницы, вам может потребоваться доступ к ней, например unsafeWindow.session.name. См .: Как получить доступ к объектам `окна` (целевой страницы), когда установлены значения @grant? .




Вы заявляете, что хотите использовать экземпляр или версию jQuery страницы. Для этого редко есть веская причина. И код, показанный в этом вопросе, определенно не выиграет от этого.

Но, , если ваш пользовательский скрипт не использует какие-либо функции GM , вы можете сделать это в режиме @grant none, например:

// ==UserScript==
// @name     _Changing the title text on some page.
// @match    *://YOUR_SERVER.COM/YOUR_PATH/*
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    none
// ==/UserScript==

waitForKeyElements (".page-breadcrumb", addAccountNameToTitle);

function addAccountNameToTitle (jNode) {
    $('title').text (session.name + " | " + $('title').text() );
}
...