waitForKeyElements在某些浏览器上没有等待ajax加载的数据

waitForKeyElements not waiting for ajax loaded data on some browsers?

本文关键字:ajax 等待 加载 数据 浏览器 waitForKeyElements      更新时间:2023-09-26

在我的Greasemonkey/Tampermonkey脚本中,它在Google Chrome中运行得很好,但在Firefox中:

waitForKeyElements ("table#ID-rowTable tr td span._GAmD", replaceAffid);

没有等待AJAX加载的内容。

以下是我的脚本的相关部分:

// ==UserScript==
// @name        ChangeProvider
// @description Change Provider Name
// @include     https://analytics.google.com/analytics/web/*
// @version     1
// @grant       GM_xmlhttpRequest
// ==/UserScript==
<snip>...
waitForKeyElements ("table#ID-rowTable tr td span._GAmD", replaceAffid);
<snip>...
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);
<snip>...


完整的代码位于pastebin.com。

问题是:

  1. waitForKeyElements()需要jQuery

  2. 您的脚本必须要么提供jQuery(推荐),要么使用@grant none模式并在已经使用jQuery的页面上运行(这是一种脆弱的操作方式,也称为"定时炸弹代码")。

  3. Tampermonkey有一个错误和可能的安全弱点,因此它并不总是沙箱正确。这意味着脚本可以(有时)看到页面的jQuery,即使@grant不是none.。这允许脚本在Chrome中运行(目前),但依赖它是一件非常危险的事情。

  4. Firefox在使用@grant GM_ ...时正确地沙盒作用域,因此脚本无法看到页面的jQuery

  5. 如果您查看了Firefox的浏览器控制台,您会看到错误消息,指出问题所在。

解决方案是:不要在没有@requireingjQuery的情况下使用waitForKeyElements
事实上,您应该同时需要这两个库,如本答案所示,因为它(A)运行速度更快,(B)在安装/编辑用户脚本时只获取一次代码,(C)使代码更干净、更容易地进行查找。

所以,你的整个脚本会变成这样:

// ==UserScript==
// @name        GoogleAnalytics Change Provider
// @description Change Provider Name
// @include     https://analytics.google.com/analytics/web/*
// @version     1
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require     https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant       GM_xmlhttpRequest
// ==/UserScript==
var providers = new Array ();
GM_xmlhttpRequest ( {
    method: "GET",
    url: "http://localhost:3000/api/t2_provider_list",
    onload: function (response) {
        var provider_list = JSON.parse (response.responseText);
        for (i = 0; i < provider_list.length; i++) {
            providers[provider_list[i].analytics_prefix] = provider_list[i].provider_name;
        }
        waitForKeyElements ("table#ID-rowTable tr td span._GAmD", replaceAffid);
    }
} );
/*--- replaceAffid ():  Match the fields with a given pattern 
and replace with the provider name and affid
*/
function replaceAffid () {
    console.log (providers);
    var regExp = /([a-z,A-Z,0-9]+)---([a-z,A-Z,0-9,_,-]+)/g;
    var spans = document.evaluate ("//span[contains(@class, '_GAmD') and not(contains(@class, '_GAe'))]/text()", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    console.log (spans);
    for (var i = 0; i < spans.snapshotLength; i++) {
        match = regExp.exec (spans.snapshotItem (i).textContent);
        if (match != null) {
            if (typeof providers[match[1]] === undefined) {
                // do nothing
            } else {
                spans.snapshotItem (i).textContent = "Provider: " + providers[match[1]] + " 'n'r  Affid: " + match[2];
            }
        }
    }
}

最后,看起来像是粘贴了waitForKeyElements的旧版本
自2012年5月以来,该功能的顶部有以下文本:

重要提示:此函数要求脚本加载jQuery。

如果你从我的一个旧答案中拿走了你的函数副本,我道歉。我只是更新了它以避免这种混乱的重复。