In background.html how can I access the current webpage to get the dom

In background.html, I want to get the current dom webpage. such as "getElementById ()

+2


a source to share


2 answers


For this, you will need to use Message Passing . Message passing is needed so you can communicate with the DOM, and the only way to communicate with the DOM is through Content-Scripts. I will show you two ways you can do this:

Method 1

Each time you visit the page, listen for an add request

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>

      

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.
});

      



Method 2

Execute content script only when needed:

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>

      

execute.js

chrome.extension.sendRequest({data: document.getElementById('header').innerHTML});

      

+6


a source


Press CTRL + SHIFT + I for developer interface for CTRL + U for source



-4


a source







All Articles