当前位置: 首页 > 面试题库 >

当页面被history.pushState和ajax调用更改时插入内容脚本

郎吉星
2023-03-14
问题内容

我遇到了将内容脚本插入页面的问题,该脚本已被history.pushState和ajax调用更改。我找到了类似的主题,但是该解决方案对我不起作用(该解决方案是使用chrome.webNavigation.onHistoryStateUpdated和“
popstate”事件)。

这是我清单的一部分:

"content_scripts": [
    {
      "matches": ["https://vk.com/audios*", "https://vk.com/al_audio.php*"],
      "js": ["jquery-2.1.4.min.js", "getListOfSongs.js"]
    }
  ]

chrome.webNavigation.onHistoryStateUpdated
仅在我导航到另一个页面时有效,如果我在序列中多次导航到同一页面则什么也没有发生。例如:它在以下情况下有效

1)转到https://vk.com/audios *-第一次打开页面或重新加载

2)转到https://vk.com/some_other_page-ajax调用

3)转到https://vk.com/audios *-ajax调用

什么时候不起作用

1)转到https://vk.com/audios *-第一次打开页面或重新加载

2)再次转到https://vk.com/audios -ajax调用,此时内容脚本未注入
3)再次转到https://vk.com/audios
-ajax调用,位于这一点内容脚本没有注入,依此类推

每次我第二次单击同一页面时,都会生成以下请求:

https://vk.com/al_audio.php?__query=audios
*&_ ref = left_nav&_smt = audio%3A2&al = -1&al_id = **&_ rndVer
= 60742

(要求的参数可能会有所不同)

同样, 在这种情况下, JQuery .ajaxComplete 不会捕获任何事件。

而且pushState不会触发“ popstate”事件,因此我无法使用window.onpopstate事件

我可能会使用 chrome.webNavigation.onDOMContentLoaded
chrome.webNavigation.onCompleted, 但是当我重新加载页面时,这些事件发生的时间 不止一次
,因此脚本将被多次注入。

这种情况下最好的解决方案是什么?


问题答案:

我可以想到两种方法:

1-使用计时器检查脚本是否仍然存在,否则,请再次添加…
2-检查ajax调用,如果它们的URL与删除脚本的URL之一匹配,请再次添加脚本。

即使在ajax调用之后,您的脚本(清单中定义的脚本)仍然存在,只是不再运行(不确定历史记录推送器会发生什么)。因此,我假设您只需要阅读一些元素或重新运行Stript。我以为您添加了附加html标记的脚本。

因此,您需要读取某些元素或重新运行某些代码

1-计时器方法-我为希望添加到页面中某个 目标元素的* 任何元素 (不仅是脚本)创建了解决方案*

它使用计时器检查目标元素是否存在。当找到目标元素时,就添加我的元素。然后调整计时器以检查我的元素是否仍然存在。如果没有,请再次添加。

您只需appendChildPersistent要打一次电话,这将在您浏览时始终保持活动状态。

var timers = {}; //stores the setInterval ids

//this is the only method you need to call
//give your script an `id` (1)
//the child is your script, it can be anything JQuery.append can take
//toElem is the Jquery "SELECTOR" of the element to add your script into.
//I'm not sure what would happen if toElem were not a string.
//callback is a function to call after insertion if desired, optional.
appendChildPersistent = function(id, child, toElem, callback)
{
    //wait for target element to appear
    withLateElement(toElem, function(target)
    {
        target.append(child); //appends the element - your script                                                                                                           
        if (typeof callback !== 'undefined') callback(); //execute callback if any

        //create a timer to constantly check if your script is still there
        timers[id] = setInterval(function()
        {                                       
            //if your script is not found, clear this timer and tries to add again          
            if (document.getElementById(id) === null)
            {
                clearInterval(timers[id]);
                delete timers[id];
                appendChildPersistent(id, child, toElem, callback);
            }
        },3000);

    });
}

//this function waits for an element to appear on the page
//since you can't foresee when an ajax call will finish
//selector is the jquery selector of the target element
//doAction is what to do when the element is found
function withLateElement(selector, doAction)
{   
    //checks to see if this element is already being waited for                             
    if (!(selector in timers))
    {
        //create a timer to check if the target element appeared                                                            
        timers[selector] = setInterval(function(){              
            var elem = $(selector);

            //checks if the element exists and is not undefined
            if (elem.length >= 0)
            {
                if (typeof elem[0] !== 'undefined')
                {
                    //stops searching for it and executes the action specified
                    clearInterval(timers[selector]);
                    delete timers[selector];
                    doAction(elem);
                }
            }
        }, 2000);
    }                                                           
}

(1)在脚本标签中添加ID似乎不是问题:为脚本标签提供ID

2-捕获ajax调用

一种选择是使用chrome.webRequest。但是奇怪的是,这对我没有用。下面是另一个选择。

对于这种情况,请检查此答案, 不要忘 了在那里阅读与 Chrome扩展程序
相关的答案。只有遵循整个过程,它才起作用。幸运的是,我今天进行了测试,它效果很好:p

在这里,您要做的是更改XMLHttpRequest方法opensend在调用它们时进行检测(并可能也获取参数)。

但是,在Google扩展程序中,绝对有必要 在页面中注入Stript (不是后台页面或脚本注入内容脚本,而是内容脚本向 dom中
注入一些代码,如下所示)。

var script = document.createElement('script');
script.textContent = actualCode; //actual code is the code you want to inject, the one that replaces the ajax methods
document.head.appendChild(script); //make sure document.head is already loaded before doing it
script.parentNode.removeChild(script); //I'm not sure why the original answer linked removes the script after that, but I kept doing it in my solution

这是至关重要的,因为该扩展程序试图创建一个隔离的环境,并且您XMLHttpRequest对此环境所做的更改将完全不参与。(这就是为什么JQuery.ajaxComplete似乎不起作用的原因,您需要在页面中注入脚本才能使其工作-
请在此处查看)

在此纯JavaScript解决方案中,您将替换方法:

//enclosing the function in parentheses to avoid conflict with vars from the page scope
(function() {
    var XHR = XMLHttpRequest.prototype;

    // Store the orignal methods from the request
    var open = XHR.open;
    var send = XHR.send;

    // Create your own methods to replace those

    //this custom open stores the method requested (get or post) and the url of the request
    XHR.open = function(method, url) {
        this._method = method; //this field was invented here
        this._url = url; //this field was invented here
        return open.apply(this, arguments); //calls the original method without any change

        //what I did here was only to capture the method and the url information
    };


    //this custom send adds an event listener that fires whenever a request is complete/loaded
    XHR.send = function(postData) {
        //add event listener that fires when request loads
        this.addEventListener('load', function() {
            //what you want to do when a request is finished
            //check if your element is there and readd it if necessary
            //if you know the exact request url, you can put an if here, but it's not necessary

            addMyElementsToPage(); //your custom function to add elements
            console.log("The method called in this request was: " + this._method);
            console.log("The url of this request was: " + this._url);
            console.log("The data retrieved is: " + this.responseText);

        });

        //call the original send method without any change
        //so the page can continue it's execution
        return send.apply(this, arguments);

        //what we did here was to insert an interceptor of the success of a request and let the request continue normally
    };
})();


 类似资料:
  • 问题内容: 我有一个带有对话框窗口的页面,该页面将ajax发布数据发送到服务器并接收响应。在开发过程中,可能有两种响应- 一种常规(这不是问题)或一种有错误。服务器返回代码500和包含大量调试信息的页面。这是从框架返回的常规页面,其中包含一些javascript代码。我希望能够显示此错误页面,以防万一。 问题是,我不能简单地将返回的结果附加到body元素或在新页面中打开新链接并再次加载此错误。我只

  • 当元素的值通过JavaScript代码更改时,会发生什么事件?例如: 事件在这里没有帮助,因为更改值的不是用户。 在Chrome上测试时,事件不会被激发。也许是因为元素没有失去焦点(它没有获得焦点,所以不能失去焦点)?

  • 问题内容: 我有一个div,其中包含数据库的一些文本: 以及链接列表: 该过程应如下所示: 点击链接 Ajax使用链接的URL通过GET将数据传递到php文件/同一页面 PHP返回字符串 div更改为此字符串 问题答案: 并在您的列表中添加事件

  • 问题内容: 我正在学习如何创建Chrome扩展程序。我刚刚开始开发一个捕捉YouTube事件的工具。我想将其与YouTube Flash Player结合使用(稍后,我将尝试使其与HTML5兼容)。 manifest.json: myScript.js: 问题在于控制台为我提供了 “开始!” ,但没有 “状态已更改!” 当我播放/暂停YouTube视频时。 将此代码放入控制台后,它就可以工作了。我

  • 问题内容: 我正在使用AJAX将表单数据发送到建立并发送html电子邮件的服务器php文件。我在服务器php文件中回显了部分数据。回显的html生成一个表,我希望用户在纸上打印。我想打开默认的浏览器打印对话框,以便用户可以打印他/她看不到的表。我不在乎是否必须打开一个新选项卡才能显示回显的内容。这有可能吗? 问题答案: 返回该html表单ajax请求,然后使用javascript打印 此代码未经测

  • 问题内容: 我正在尝试制作一个小的桌面应用程序,该应用程序应显示剪贴板的内容(如果它是字符串)。我已经完成了一个构造函数,并且构造函数运行良好,现在,我只想在将文本复制到OS的剪贴板中时调用类似的方法。我对此很陌生,因此不胜感激!告诉我应该以某种方式使用中断… 问题答案: 您可以调用Clipboard.addFlavorListener来侦听来自操作系统的剪贴板更新: 一些注意事项: 要启动您的应