In background.html,I want to get current web page dom. such as "getElementById()
A:
Hit CTRL+SHIFT+I for the developer UI oder CTRL+U for the source
Micheal Werner
2010-05-06 08:40:15
I is developing chrome extension ,not view web page..
Gio
2010-05-06 08:52:31
+1
A:
Hi Gio,
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
2010-05-06 22:13:17