从"popup.html"访问当前选项卡DOM对象?

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)

现在请记住设置清单以包含内容脚本和选项卡权限.

  • [**`chrome.tabs.getSelected`自Chrome 33**后不推荐使用](https://developer.chrome.com/extensions/tabs#method-getSelected); [**`chrome.tabs.sendRequest`自Chrome 33以来已弃用**](https://developer.chrome.com/extensions/tabs#method-sendRequest); [**`chrome.extension.onRequest`自Chrome 33**后不再使用](https://developer.chrome.com/extensions/extension#event-onRequest). (6认同)
  • 上面的例子有用吗?AFAIK发送响应将dom序列化为json,这可能由于dom对象的圆形结构而导致错误. (3认同)

Tim*_*Law 8

这是最新的修复:

弹出窗口.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