2009-12-26 95 views

回答

24

默認情況下,在popup.js/popup.html中,「文檔」對象僅引用擴展的彈出窗口的文檔。要獲取特定選項卡的DOM(例如當前活動選項卡),您需要使用content scripts communications。例如,我們需要通過popupextension的請求發送到您的內容腳本,所以在popup.html你做這樣的事:

chrome.tabs.getSelected(null, function(tab) { 
    // Send a request to the content script. 
    chrome.tabs.sendRequest(tab.id, {action: "getDOM"}, function(response) { 
    console.log(response.dom); 
    }); 
}); 

現在在內容腳本,我們需要從listen for those events未來延伸,所以在一些文件中,我們命名爲dom.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
if (request.action == "getDOM") 
    sendResponse({dom: "The dom that you want to get"}); 
else 
    sendResponse({}); // Send nothing.. 
}); 

現在還記得設置你的manifest包含內容腳本和標籤許可。

+0

我的意思是DOM是文檔對象模型...謝謝 – 2009-12-27 12:54:05

+1

是的,我在示例中展示的是在Chrome擴展中完成的同步消息。我返回了一個字符串「你想得到的dom」,但實際上,你可以返回任何你想要的DOM。如果你想獲得所有的東西,你可以做「sendResponse({dom:document.getElementsByTagName(」body「)[0]});」 – 2009-12-28 03:08:05

+3

做了上面的例子嗎? AFAIK發送響應會將dom序列化爲json,這可能會導致由於dom對象的圓形結構而導致的錯誤。 – 2011-06-28 14:44:39

3

這個答案似乎不適用於最新的API。這是一個工作示例。

popup.js:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    var tab = tabs[0]; 
    console.log(tab.url, tab.title); 
    chrome.tabs.getSelected(null, function(tab) { 
     chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(msg) { 
      msg = msg || {}; 
      console.log('onResponse', msg.farewell); 
     }); 
    }); 
}); 

getDescription.js:manifest.json中的

window.onload = function() { 
    chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) { 
     console.log('onMessage', msg); 
     if (msg.greeting == "hello") { 
      sendResponse({farewell: "goodbye"}); 
     } else{ 
      sendResponse({}); 
     } 
    }); 
}; 

相關部分:

{ 
    "permissions": [ 
     "tabs" 
    ], 

    "content_scripts": [ 
    { 
     "matches": ["http://*/*", "https://*/*"], 
     "js": ["getDescription.js"] 
    } 
    ] 
} 
1

這是最新的補丁:

popup.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
    chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) { 
     console.log(response.farewell); 
    }); 
}); 

(注:以上的console.log(response.farewell)是popup.html,不是你的當前選項卡)

contentscript.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
    if (request.greeting == "hello") 
     sendResponse({farewell: "goodbye"}); 
    }); 

來源:https://developer.chrome.com/extensions/messaging