Kha*_*ied 33 javascript google-chrome
我正在为Google Chrome浏览器开发扩展程序.我无法弄清楚如何从"popup.html"页面访问当前标签DOM对象.有什么建议?
Moh*_*our 26
默认情况下,在popup.js/popup.html中,"document"对象仅引用扩展的弹出窗口文档.要获取特定选项卡的DOM(例如当前活动的选项卡),您需要使用内容脚本通信.例如,我们需要通过弹出窗口从扩展程序向您的内容脚本发送请求,因此在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);
});
});
Run Code Online (Sandbox Code Playgroud)
现在在内容脚本中,我们需要监听来自扩展的那些事件,所以在某个文件中我们命名为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..
});
Run Code Online (Sandbox Code Playgroud)
现在请记住设置清单以包含内容脚本和选项卡权限.
这是最新的修复:
弹出窗口.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Run Code Online (Sandbox Code Playgroud)
(注意:上面的 console.log(response.farewell) 是针对 popup.html 的,不是你当前的标签页)
内容脚本.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
Run Code Online (Sandbox Code Playgroud)
来源:https : //developer.chrome.com/extensions/messaging
| 归档时间: |
|
| 查看次数: |
22117 次 |
| 最近记录: |