Reputation: 41
In background.html,I want to get current web page dom. such as "getElementById()
Upvotes: 4
Views: 4399
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:
Having every visited page listen for an extension request
<html>
<script>
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getHTML"}, function(response) {
console.log(response.data);
});
});
</script>
</html>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "getHTML")
sendResponse({data: document.getElementById('header').innerHTML});
else
sendResponse({}); // snub them.
});
Only execute a content script whenever you need to:
<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>
chrome.extension.sendRequest({data: document.getElementById('header').innerHTML});
Upvotes: 7
Reputation: 5
Hit CTRL+SHIFT+I for the developer UI oder CTRL+U for the source
Upvotes: -4