在background.html中,如何访问当前网页以获取dom

Gio*_*Gio 4 google-chrome google-chrome-extension

在background.html中,我希望获得当前的网页dom.例如"getElementById()

Moh*_*our 7

为此,您需要使用消息传递.需要消息传递以允许您与DOM进行通信,并且与DOM通信的唯一方法是通过Content-Scripts.我将向您展示两种方法,您可以这样做:

方法1

让每个访问过的页面都监听扩展请求

background.html

<html>
<script>
chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
    console.log(response.data);
  });
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)

content_script.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getHTML")
      sendResponse({data: document.getElementById('header').innerHTML});
    else
      sendResponse({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)

方法2

只在需要时执行内容脚本:

background.html

<html>
<script>
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(tab.id, {file: 'execute.js'});
});

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
  console.log('Data Recieved: ' + request.data);
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)

execute.js

chrome.extension.sendRequest({data: document.getElementById('header').innerHTML});
Run Code Online (Sandbox Code Playgroud)