5

我正在爲網站創建一個小的Google Chrome擴展,並且我想在特定頁面上更改一些html。如何通過history.pushState更改頁面時如何在Google Chrome擴展插入內容腳本?

問題是,網站通過ajax加載他的內容,並大量使用history.pushState API。 所以,我說這個東西來體現:當我打開網頁第一次或重裝它

"content_scripts": [ 
    { 
    "matches": ["http://vk.com/friends"], 
    "js": ["js/lib/jquery.min.js", "js/friends.js"],  
    }, 
] 

,一切工作正常。 但是,當我在網頁之間瀏覽時,chrome不會將我的腳本插入「/ friends」頁面。我認爲這是因爲URL實際上沒有改變。他們使用history.pushState()等,鉻不能再次插入/重新運行我的腳本。

有沒有解決方案?

回答

3

您可以在內容腳本中添加window.onpopstate事件並偵聽它,當事件觸發時,您可以再次重新運行內容腳本。

參考

一個)extension.sendMessage()

b)中extension.onMessage().addListener

c)中tabs.executeScript()

d)history.pushState()

E)window.onpopstate

示例演示:

的manifest.json

確保內容腳本注入URL和所有API的標籤有足夠的權限在manifest文件

{ 
    "name": "History Push state Demo", 
    "version": "0.0.1", 
    "manifest_version": 2, 
    "description": "This demonstrates how push state works for chrome extension", 
    "background":{ 
     "scripts":["background.js"] 
    }, 
    "content_scripts": [{ 
     "matches": ["http://www.google.co.in/"], 
     "js": ["content_scripts.js"] 
    }], 
    "permissions": ["tabs","http://www.google.co.in/"] 
} 

content_scripts.js

跟蹤onpopstate事件,併發送至後臺頁面的請求腳本的重播

window.onpopstate = function (event) { 
    //Track for event changes here and 
    //send an intimation to background page to inject code again 
    chrome.extension.sendMessage("Rerun script"); 
}; 

//Change History state to Images Page 
history.pushState({ 
    page: 1 
}, "title 1", "imghp?hl=en&tab=wi"); 

background.js

軌道針對來自內容腳本的請求T和執行腳本到當前頁面

//Look for Intimation from Content Script for rerun of Injection 
chrome.extension.onMessage.addListener(function (message, sender, callback) { 
    // Look for Exact message 
    if (message == "Rerun script") { 
     //Inject script again to the current active tab 
     chrome.tabs.executeScript({ 
      file: "rerunInjection.js" 
     }, function() { 
      console.log("Injection is Completed"); 
     }); 
    } 
}); 

rerunInjection。JS

一些瑣碎的代碼

console.log("Injected again"); 

輸出

enter image description here

讓我知道如果你需要更多的信息。

+3

順便說一句,pushState的不火「popstate」事件,所以這段代碼不起作用。 –

7

我能夠得到這個工作。從Chrome Extension docs for webNavigation

您需要設置webNavigation權限manifest.json的

"permissions": [ 
    "webNavigation" 
    ], 

然後在background.js

chrome.webNavigation.onHistoryStateUpdated.addListener(function(details) { 
     console.log('Page uses History API and we heard a pushSate/replaceState.'); 
     // do your thing 
    }); 
相關問題