In background.html,I want to get current web page dom. such as "getElementById()
Asked
Active
Viewed 4,313 times
4
-
Yeah, how can i get current web page dom? – Gio May 06 '10 at 08:45
2 Answers
7
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});

Mohamed Mansour
- 39,445
- 10
- 116
- 90