当页面被 history.pushState 和 ajax 调用更改时插入内容脚本
insert content script when page was changed by history.pushState and ajax call
我在将内容脚本插入由 history.pushState 和 ajax 调用更改的页面时遇到了问题。我在 Whosebug 找到了 similar topic,但该解决方案对我不起作用(该解决方案是使用 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 调用之后,它也不会再次 运行(不确定历史推送器会发生什么)。所以,我假设您只需要重新添加一些元素或重新运行 脱衣舞。我想你添加的脚本附加了一个 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好像问题不大:Giving the script tag an ID
2 - 捕获 ajax 个调用
一个选项是使用 chrome.webRequest。但奇怪的是,这对我不起作用。下面是另一个选项。
对于这种情况,请检查this answer,并且不要忘记阅读Chrome扩展的相关答案 在那里。只有您遵循整个程序,它才会起作用。幸运的是,我今天测试了它并且效果很好 :p
在这里,您要做的是更改 XMLHttpRequest
方法 open
和 send
以检测(并可能也获取参数)调用它们的时间。
但是,在 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 似乎不起作用的原因,您需要在页面中注入脚本才能使其工作 - look here)
在 this pure javascript solution 中,您替换方法:
//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
};
})();
我在将内容脚本插入由 history.pushState 和 ajax 调用更改的页面时遇到了问题。我在 Whosebug 找到了 similar topic,但该解决方案对我不起作用(该解决方案是使用 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 调用之后,它也不会再次 运行(不确定历史推送器会发生什么)。所以,我假设您只需要重新添加一些元素或重新运行 脱衣舞。我想你添加的脚本附加了一个 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好像问题不大:Giving the script tag an ID
2 - 捕获 ajax 个调用
一个选项是使用 chrome.webRequest。但奇怪的是,这对我不起作用。下面是另一个选项。
对于这种情况,请检查this answer,并且不要忘记阅读Chrome扩展的相关答案 在那里。只有您遵循整个程序,它才会起作用。幸运的是,我今天测试了它并且效果很好 :p
在这里,您要做的是更改 XMLHttpRequest
方法 open
和 send
以检测(并可能也获取参数)调用它们的时间。
但是,在 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 似乎不起作用的原因,您需要在页面中注入脚本才能使其工作 - look here)
在 this pure javascript solution 中,您替换方法:
//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
};
})();