2017-06-01 77 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

相關問題