问题
I am building an extension (some injected js) that adds some buttons to a youtube page, which works fine. My issue is that when a user clicks on another video (say in the right hand side list), the next video is loaded without an actual page reload. Is there any way to detect this change so that I can rerun my code?
I have already tried things like binding to the hashchange
event, to no avail.
回答1:
The idea is simple:
- Use
background.js
to listen for url changes to a specific youtube tab usingchrome.tabs.onUpdated
- Once tab change is detected, send the new URL to the content-script running in that tab
The background page listens for URL changes to other tabs also but I'm pretty sure you can figure out how to fix that.
manifest.json
{
"manifest_version": 2,
"name": "Tab url change detection",
"version": "1.0",
"background": {
"persistent":true,
"page":"bg.html"
},
"content_scripts": [{
"matches": ["http://www.youtube.com/*"],
"js": ["app.js"]
}
],
"permissions": [
"tabs",
"http://www.youtube.com/*"
]
}
background.html
<script src="background.js"></script>
background.js
//Listen for when a Tab changes state
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
if(changeInfo && changeInfo.status == "complete"){
console.log("Tab updated: " + tab.url);
chrome.tabs.sendMessage(tabId, {data: tab}, function(response) {
console.log(response);
});
}
});
app.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
//here we get the new
console.log("URL CHANGED: " + request.data.url);
});
回答2:
I was recently struggling with this and I figured out what to do. I'm not sure if this is the best way to do it, but it doesn't rely on a background.js
file.
var oldURL= ""
//window.setInterval takes a function and executes it after
//a given time (defined by the second parmeter)in miliseconds
var urlChangeHandler = window.setInterval(checkUrlChange, 500)
function checkURLChange(){
newURL = document.URL;
if(newURL !== oldURL){
doSomething();
oldURL = newURL;
}
}
回答3:
I hope this will be helpful for somebody.
var old_url = '';
var mutationObserver = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (location.href != old_url) {
old_url = location.href;
console.log('URL was changed');
}
});
});
mutationObserver.observe(document.documentElement, {childList: true, subtree: true});
来源:https://stackoverflow.com/questions/21657319/detect-youtube-video-change-with-injected-javascript