【发布时间】:2009-12-26 20:02:33
【问题描述】:
我正在为 Google Chrome 浏览器开发一个扩展程序。 我不知道如何从“popup.html”页面访问当前选项卡 DOM 对象。 有什么建议吗?
【问题讨论】:
我正在为 Google Chrome 浏览器开发一个扩展程序。 我不知道如何从“popup.html”页面访问当前选项卡 DOM 对象。 有什么建议吗?
【问题讨论】:
默认情况下,在 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 以包含内容脚本和选项卡权限。
【讨论】:
这是最新的修复:
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的,不是你当前的tab)
contentscript.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
【讨论】:
这个答案似乎不适用于最新的 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:
window.onload = function() {
chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
console.log('onMessage', msg);
if (msg.greeting == "hello") {
sendResponse({farewell: "goodbye"});
} else{
sendResponse({});
}
});
};
manifest.json 的相关部分:
{
"permissions": [
"tabs"
],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["getDescription.js"]
}
]
}
【讨论】: