0
我發現有很多帖子教我們如何使用sendRequest和OnRequest.addListener
函數將內容腳本中的值傳遞給後臺腳本。Chrome-Ext:如何將參數值從popup.js/background.js傳遞到內容腳本?
但是,我想將用戶輸入參數傳遞給內容腳本。我怎樣才能做到這一點?
我發現有很多帖子教我們如何使用sendRequest和OnRequest.addListener
函數將內容腳本中的值傳遞給後臺腳本。Chrome-Ext:如何將參數值從popup.js/background.js傳遞到內容腳本?
但是,我想將用戶輸入參數傳遞給內容腳本。我怎樣才能做到這一點?
根據您注入內容腳本的方式,您可以採用不同的方式。首先,如果您使用的匹配模式,並通過清單注射,你需要基於content script
一些事件的數據,那麼你會想要做這樣的事情:
內容腳本
chrome.extension.sendMessage({text:"getStuff"},function(reponse){
//This is where the stuff you want from the background page will be
if(reponse.stuff == "test")
alert("Test received");
});
Background.js
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
if(message.text == "getStuff")
sendResponse({stuff:"test"}); //This would be where you send your stuff
});
如果你正在做計劃注入和你有時間,你是注入數據,然後事端像這樣會工作。我假設你已經知道如何讓你希望注入標籤:
Background.js
//given tab is the tab ID you already have
chrome.tabs.executeScript(tab,{file:"contentScript.js"},function(){
chrome.tabs.sendMessage(tab, {stuff:"test"});
});
contentScript.js
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
//This is where the stuff you want from the background page will be
if(message.stuff == "test")
alert("Test received");
});
如果您需要從彈出窗口發送數據到已經注入的內容腳本,然後你可以這樣做:
Popup.js
chrome.tabs.query({active:true,currentWindow:true}, function(tab) {
chrome.tabs.sendMessage(tab[0].id, {stuff:"test"});
});
contentScript.js
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
//This is where the stuff you want from the background page will be
if(message.stuff == "test")
alert("Test received");
});
不管如何注入腳本這將工作,只要你想要的選項卡中選擇。
謝謝。但在content_script中,我應該定義什麼運行級別? – 2013-03-25 06:07:07
@KitHo除非我需要它運行得更早,否則我將它作爲默認值,我認爲是「文檔閒置」。我還經常將它封裝在一個'document.ready'上面,以確保在我嘗試觸摸DOM之前加載所有內容。 – BeardFist 2013-03-25 07:50:32