Eric
Eric

Reputation: 31

Chrome extension: Attaching current tab to popup and then going through its DOM

I'm in the process of making a Google Chrome extension, and encountered a problem.

I'm trying to upload and search through the DOM inside the popup.html.

Here is how I get the current tab (I found the script somewhere, credit doesn't belong to me):

 chrome.windows.getCurrent(function(w) {
      chrome.tabs.getSelected(w.id,function (response){
  )};

My problem is this: I need to traverse through the DOM of the response. When trying to do so manually, I couldn't, as the response variable was now undefined for some reason, so using the Console isn't an option. When trying to alert the response in the html file, it came as a object. Then, I tried to navigate through the response as if it has been the 'document' object, but no luck either.

Any help will be appreciated greatly.

Upvotes: 3

Views: 2713

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 29214

You can get the selected tab for your popup by passing null as the window id to getSelected. () In your popup you can listen for extension events and execute a script to push the content to your popup:

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        if (request.action == "content")
        {
            console.log('content is ' + request.content.length + ' bytes');
        }
    });
chrome.tabs.getSelected(null, function(tab) {
        chrome.tabs.executeScript(tab.id, { file: 'scripts/SendContent.js' } );
    });

And finally the content script... I have it as "scripts/SendContent.js" in my extension folder, but the script is simple enough you could execute it by putting the code in the code property instead of the name in the file property of the object you pass to executeScript:

    console.log('SendContent.js');
    chrome.extension.sendRequest( {
            action: "content",
            host: document.location.hostname,
            content: document.body.innerHTML
        }, function(response) { }
    );

Result:

POPUP: content is 67533 bytes

If you're having trouble, use console.log() and right-click on your page or browser action to inspect it and read your messages on the console (or debug your script from there).

Upvotes: 4

Greg
Greg

Reputation: 10788

I believe popups are sandboxed the same way that background pages are, so you'll need to use a content script to access the page DOM.

You can inject a content script with chrome.tabs.executeScript, handle your DOM traversal in the content script, then pass back the information you need from the content script to the popup using the message passing API.

I can try to elaborate on this if you give more information about the problem you're trying to solve.

Upvotes: 2

Related Questions