2017-06-01 79 views
0

我目前正在编写需要在YouTube视频上运行的Google Chrome扩展程序。我有一个内容脚本,它是一个JavaScript文件,可以完成我需要的所有工作。导航到新链接时内容脚本无法运行

它工作正常,唯一需要注意的是,无论何时点击链接转到新视频,它都不会立即运行JavaScript代码;您需要重新加载页面才能使其工作。

manifest.json的

{ 
"name": "Title", 
"description": "description", 
"version": "0.5", 
"permissions": [ 
    "webNavigation", 
    "activeTab", 
    "tabs", 
    "*://*.youtube.com/*" 
], 
"browser_action": { 
     "default_icon": {     
     "16": "image.png"   
     }, 
     "default_title": "name",  
     "default_popup": "popup.html"   
}, 

"content_scripts": [ 
{ 
    "matches": ["*://*.youtube.com/*"], 
    "js": ["blocker.js"], 
    "run_at": "document_end" 
} 
], 
"manifest_version": 2 
} 

blocker.js

myfunction(); 
function myfunction(){ 
    //manipulate the HTML DOM 
} 
+0

的可能的复制[Chrome扩展没有在YouTube上加载浏览器的导航(https://stackoverflow.com/questions/18397962/chrome-extension-is-not-loading-on-browser-navigation- (如何检测Youtube上的页面导航并在页面呈现之前修改HTML)?(https://stackoverflow.com/questions/34077641/how-to-detect-page-navigation-on-youtube-and -modify-html-before-page-is-rendered) –

回答

0
myfunction(); 
function myfunction(){ 
    //manipulate the HTML DOM 
} 

你可以把一个时间间隔,以检测该URL changes

var currentURL = location.href; 
setInterval(function() { 
    if(location.href != currentURL) { 
     myfunction(); 
     currentURL = location.href 
    } 
}, 100); 

,但我用这个

var currentURL = location.href; 
window.onclick=function(){ 
    if(currentURL!==location.href){ 
    myfunction(); 
    currentURL = location.href 
    /*some code*/ 
    } 
} 

HTML5引入了hashchange事件,它允许你为URL哈希值发生变化的通知没有注册轮询他们的计时器。

window.onhashchange = function (event) { 
    console.log(location.hash, event.oldURL, event.newURL); 
    myfunction(); 
} 
+0

这不适合我。同样的问题正在发生。当我导航到新的YouTube页面时,脚本将不会运行;我需要刷新页面才能正常工作。 – samsore

+0

@samsore请参阅更新 – AvrilAlejandro

+0

我在我的JavaScript函数中放置了window.onhashchange部分,但它仍不能解决问题。我的JavaScript文件根本没有被触发,所以它不能在代码中运行任何东西。 – samsore

相关问题