Gio
Gio

Reputation: 41

In background.html,how can I access current web page to get dom

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

Upvotes: 4

Views: 4399

Answers (2)

Mohamed Mansour
Mohamed Mansour

Reputation: 40159

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

Method 1

Having every visited page listen for an extension 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

Only execute a content script whenever you need to:

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

Upvotes: 7

Micheal Werner
Micheal Werner

Reputation: 5

Hit CTRL+SHIFT+I for the developer UI oder CTRL+U for the source

Upvotes: -4

Related Questions