默认情况下,在popup.js / popup.html中,“document”对象仅引用扩展的弹出窗口的文档。要获取特定选项卡(例如当前活动的选项卡)的DOM,您需要使用
content scripts communications.例如,我们需要通过
popup将请求从
extension发送到内容脚本,因此在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包括内容脚本和tab权限。