当通过history.pushState和ajax调用更改页面时,如何插入内容脚本

6
我遇到了一个问题,即向由历史记录和ajax调用更改的页面中插入内容脚本。我在stackoverflow上找到了类似主题,但该解决方案对我无效(该解决方案使用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)进行ajax调用以访问https://vk.com/some_other_page

3)进行ajax调用以访问https://vk.com/audios*。

但是,在以下情况下它不起作用:

1)首次打开或重新加载https://vk.com/audios*页面。

2)再次进行ajax调用以访问https://vk.com/audios*,此时内容脚本未注入。
3)再次进行ajax调用以访问https://vk.com/audios*,此时内容脚本未注入,以此类推。

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

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.onDOMContentLoadedchrome.webNavigation.onCompleted,但是当我重新加载页面时,这些事件会发生多次,因此脚本将被注入多次。

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


我在stackoverflow上找到了类似的话题,但那个解决方案对我不起作用。你需要更好地解释一下。 - Xan
1
我在整篇文章中已经解释过了。在该主题中,建议使用chrome.webNavigation.onHistoryStateUpdated和popstate事件作为解决方案,但正如我上面所提到的,这个解决方案对我不起作用。 - ivan_ochc
你能链接到你找到的解决方案吗? - Xan
请参考我的帖子中添加的链接,了解如何在页面变化后通过Google Chrome扩展程序插入内容脚本。 - ivan_ochc
另外,请定义“多次导航到同一页”。 - Xan
显示剩余3条评论
1个回答

4
我能想到两种可能的方法:
1 - 使用定时器检查脚本是否存在,如果不存在,则重新添加... 2 - 检查ajax调用,如果它们的url与删除您的脚本之一的url匹配,则再次添加脚本。
即使经过ajax调用后,您定义在清单中的脚本仍然存在,但它不会再次运行(不确定历史推动器会发生什么)。因此,我假设您只需要重新添加一些元素或重新运行该脚本。我认为您是通过附加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) 对于在script标签中添加Id,似乎并不是问题:给script标签添加ID


2 - 捕获ajax调用

一种方法是使用chrome.webRequest。但奇怪的是,这对我并没有起作用。另一种选择如下。

对于这种情况,请查看这个答案,并不要忘记阅读其中与Chrome扩展程序相关的答案。只有按照整个过程操作才能使其正常工作。幸运的是,我今天测试了一下,它非常好用:p

在这里,您需要更改XMLHttpRequest方法opensend来检测(并可能获取参数),以确定它们何时被调用。

然而,在Google扩展程序中,您绝对必须将代码注入页面(不是后台页面或脚本注入内容脚本的页面,而是您的内容脚本将某些代码注入到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
    };
})();

感谢您的出色回答。我已经成功地使用了第一种解决方案。但在这种情况下,我只是检查了内容脚本添加的元素是否存在,并在该元素不存在时重新添加它。在第二种解决方案中,由于我对JavaScript的纯经验,我没有取得成功。我只是没有理解覆盖XMLHttpRequest方法的部分。我需要更改页面使用的原始XMLHttpRequest(例如vk.com/audio)吗? - ivan_ochc
看一下修改。通过替换XMLHttpReques.prototype中的sendopen,您确实改变了原始的XMLHttpRequest。但不要忘记注入部分,在Chrome扩展中绝对是必要的。否则它将什么也不做。 - Daniel Möller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接