Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当页面被history.pushState和ajax调用更改时插入内容脚本_Javascript_Ajax_Dom_Google Chrome Extension_Vk - Fatal编程技术网

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

Javascript 当页面被history.pushState和ajax调用更改时插入内容脚本,javascript,ajax,dom,google-chrome-extension,vk,Javascript,Ajax,Dom,Google Chrome Extension,Vk,我遇到了在页面中插入内容脚本的问题,该页面被history.pushState和ajax调用更改。我在stackoverflow中找到了,但该解决方案不适用于我(该解决方案使用了chrome.webNavigation.onHistoryStateUpdated和“popstate”事件) 这是我清单的一部分: "content_scripts": [ { "matches": ["https://vk.com/audios*", "https://vk.com/al_aud

我遇到了在页面中插入内容脚本的问题,该页面被history.pushState和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) 第一次进入*打开页面或重新加载

2) 转到-ajax调用

3) 转到*-ajax调用

它不工作的时候

1) 第一次进入*打开页面或重新加载

2) 再次转到*-ajax调用,此时内容脚本没有注入
3) 再次转到*-ajax调用,此时内容脚本没有注入,等等

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

*********&_ref=左导航和smt=音频%3A2&al=-1&al\U id=*********和\U rndVer=60742

(请求参数可能有所不同)

另外,JQuery.ajaxComplete在这种情况下不会捕获任何事件

pushState不会触发“popstate”事件,所以我不能使用window.onpopstate事件

我可能会使用chrome.webNavigation.onDOMContentLoadedchrome.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似乎不是问题:


2-捕获ajax调用

一个选择是使用。但奇怪的是,这对我不起作用。另一个选择如下

对于这种情况,请选中,并且不要忘了阅读中有关Chrome extension的相关答案。只有遵循整个过程,它才会起作用。幸运的是,我今天测试了它,效果很好:p

在这里,您要做的是更改
XMLHttpRequest
方法
open
send
,以便在调用参数时检测(也可能获取参数)

但是,在Google扩展中,绝对有必要在页面中注入stript(不是背景页面或脚本注入内容脚本,而是内容脚本注入一些代码到dom中,如下所示)

这是至关重要的,因为扩展试图创建一个隔离的环境,而您在该环境中对
XMLHttpRequest
所做的更改将不会参与其中。(这就是JQuery.ajaxComplete似乎无法工作的原因,您需要在页面中插入一个脚本,它才能工作-)

在中,将替换以下方法:

//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
    };
})();

“我在stackoverflow上也发现了类似的话题,但这个解决方案对我不适用”你必须更好地解释这一点,我在整篇文章中都解释过。建议使用chrome.webNavigation.onHistoryStateUpdated和popstate事件作为该主题的解决方案,但如上所述,该解决方案不适合我。您可以链接到找到的解决方案吗?还将此链接添加到我的postAlso,define“多次导航到同一页面”。谢谢您的回答。我成功地解决了第一个问题。但在本例中,我只是检查我通过内容脚本添加的元素是否存在,若该元素不存在,则重新添加它。在第二个解决方案中,我没有取得成功,因为我有使用JavaScript的纯粹经验。我只是没有参与重写XMLHttpRequest方法。我是否需要更改页面使用的原始XMLHttpRequest(例如vk.com/audio)?查看编辑。通过替换
XMLHttpRequest.prototype
中的
send
open
,您确实在更改原始
XMLHttpRequest
。但别忘了注入部分,这在镀铬扩展中是绝对必要的。否则它将什么也不做。
//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
    };
})();