1

比方說,我想要更改Chrome擴展中所選標籤的內容。我想用fly替換每次出現的come在Chrome瀏覽器中選中標籤的內容中交換一些文字

如何動態更改單詞?

到目前爲止,我到達documentreplace所有發生的單詞come,但無法將更新的內容寫入選定的選項卡。

我寫的是;

chrome.tabs.getSelected(null,function(tab) { 
    updatedContent = document.replace(/come, 'fly'); 

}); 

我該如何做到這一點?

編輯:我的錯誤,document.replace不能正常工作。編輯2:用@Haibara Ai的建議我編輯爲;

chrome.tabs.query({active: true, currentWindow: true} ,function (tabs) { 
    chrome.tabs.executeScript(tabs[0].id, { code: 'document.body.outerHTML.replace(/come/g, "fly")' }); 
}); 

但是什麼也沒有發生。也沒有錯誤。

回答

0

chrome.tabs.getSelected在擴展的上下文中被調用,而你想訪問的dom生命在網頁的過程中,你不能從背景頁面直接操作它。

達到你想要的,你可以看看chrome.tabs.executeScript,它允許你做編程注射,樣品代碼看起來像什麼:

chrome.tabs.query({active: true, currentWindow: true}, 
    (tabs) => chrome.tabs.executeScript(tabs[0].id, {code: 'document.replace(/come, "fly");'})); 

請注意document.replace不順利,你可以改用其他方法,如document.body.innerHTML.replace

順便說一句,chrome.tabs.getSelected已被棄用,請改用chrome.tabs.query{active: true}

+0

非常感謝你,但是當我在'window.onload = function(){}'中嘗試你的代碼時,它不起作用。並且給了我這個錯誤:'Uncaught SyntaxError:意外的標識符'在行'(tabs)=> chrome.tabs.executeScript(tabs [0] .id,{code:'document.replace(/ come,'fly');' });' – user6468132

+0

@ user6468132,這只是一個示例代碼,您需要使用自己的'replace'方法,並且不要忘記處理報價和權限問題。 –

+0

當我在'document.body.outerHTML.replace(/ come/g,「fly」)'的控制檯中運行相同的結果時,outerHTML被更改,但頁面中沒有任何更改。應該添加以使這些更改顯示在頁面中? – user6468132

相關問題