唯一的方法強(qiáng)制注入內(nèi)容腳本而不刷新頁(yè)面是透過(guò)程式註入。
您可以使用Chrome瀏覽器的標(biāo)籤API取得所有標(biāo)籤,並向它們注入程式碼。 例如,您可以將一個(gè)版本號(hào)儲(chǔ)存在本機(jī)儲(chǔ)存中,並在每次檢查背景頁(yè)中的版本號(hào)是否過(guò)舊時(shí)(如果是),您可以取得所有活動(dòng)標(biāo)籤並透過(guò)程式註入您的程式碼,或任何其他可以確保擴(kuò)充功能已更新的解決方案。
使用以下程式碼取得所有標(biāo)籤:
chrome.tabs.query
並向所有頁(yè)面注入您的程式碼
chrome.tabs.executeScript(tabId, {file: "content_script.js"});
有一種方法可以在升級(jí)後使內(nèi)容腳本重的擴(kuò)充功能繼續(xù)正常工作,並在安裝後立即使其生效。
安裝的方法是簡(jiǎn)單地遍歷所有視窗中的所有標(biāo)籤,並在具有匹配URL的標(biāo)籤中以編程方式註入一些腳本。
manifest.json:
"background": {"service_worker": "background.js"}, "permissions": ["scripting"], "host_permissions": ["<all_urls>"],
這些host_permissions應(yīng)與內(nèi)容腳本的matches
相同。
background.js:
chrome.runtime.onInstalled.addListener(async () => { for (const cs of chrome.runtime.getManifest().content_scripts) { for (const tab of await chrome.tabs.query({url: cs.matches})) { chrome.scripting.executeScript({ target: {tabId: tab.id}, files: cs.js, }); } } });
這是一個(gè)簡(jiǎn)化的範(fàn)例,不處理框架。您可以使用getAllFrames API並自行匹配URL,請(qǐng)參閱匹配模式的文件。
顯然,您必須在manifest.json中聲明的background page或event page腳本中執(zhí)行此操作:
"background": { "scripts": ["background.js"] },
background.js:
// Add a `manifest` property to the `chrome` object. chrome.manifest = chrome.runtime.getManifest(); var injectIntoTab = function (tab) { // You could iterate through the content scripts here var scripts = chrome.manifest.content_scripts[0].js; var i = 0, s = scripts.length; for( ; i < s; i++ ) { chrome.tabs.executeScript(tab.id, { file: scripts[i] }); } } // Get all windows chrome.windows.getAll({ populate: true }, function (windows) { var i = 0, w = windows.length, currentWindow; for( ; i < w; i++ ) { currentWindow = windows[i]; var j = 0, t = currentWindow.tabs.length, currentTab; for( ; j < t; j++ ) { currentTab = currentWindow.tabs[j]; // Skip chrome:// and https:// pages if( ! currentTab.url.match(/(chrome|https):\/\//gi) ) { injectIntoTab(currentTab); } } } });
在古老的Chrome 26及更早版本中,內(nèi)容腳本可以恢復(fù)與後臺(tái)腳本的連線。這在2013年修復(fù)http://crbug.com/168263。您可以在此答案的早期版本中看到此技巧的範(fàn)例。