I'm developing a Chrome extension that simply scans the DOM for phrases.
The only thing I need help with is grabbing the DOM content with popup, I can't find a way to return the contents of the current tab.
You can easily change the DOM without having to edit the HTML as a big piece of string. Right click on a node and select Copy. You can paste in your code editor, or for prototyping, you can paste the DOM node elsewhere in the DOM tree. The pasted node is inserted as a child of the currently selected node.
Run the extension Look for the hello world extension icon in Chrome toolbar and click on it. You should be able to see a window popup containing current tab page h1 dom element value.
Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.
Tested and works correctly:
put
"permissions": [
"tabs"
],
in your manifest.
Then, in your background.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
// LOG THE CONTENTS HERE
console.log(request.content);
});
chrome.tabs.getSelected(null, function(tab) {
// Now inject a script onto the page
chrome.tabs.executeScript(tab.id, {
code: "chrome.extension.sendRequest({content: document.body.innerHTML}, function(response) { console.log('success'); });"
}, function() { console.log('done'); });
});
So essentially, we get the current tab, run some javascript on it that gets the innerHTML and passes it back to us. We interpret the response in a callback as appropriate.
Note this does very little error checking, so you might want to brush up on message passing and the tabs API.
Edit: I've tried this out and it does work as expected. To try it yourself easily, just create a new empty extension and give it the "tabs" permission and a background page. Then go inspect background.html from chrome://extensions and go to the console. Copy in the code below, setting the chrome.tabs.getSelected
nesting on a timeout of a few seconds. When you click enter to execute the JS, quickly click to some other tab. Wait for your timeout. Then go back to inspecting background.html. The HTML of the page you clicked to will have printed to the console.
Another Edit: In general, accessing the current tab DOM as an event seems like it might be a bad model (which is probably why there isn't a great native way to do it). Have you considered either using chrome.tabs.onUpdated or content scripts to universally do something on loading/changing the DOM?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With