user1555863
user1555863

Reputation: 2607

chrome extension message passing empty div

I'm trying to pass a div from a content script as a message to my background.js of a chrome extension, in accordance with what's described officially here by Google.

Code to consider is fairly simple:

Relevant part of manifest.json:

{
  "name": "Proof of conecpt extension",
  "version": "0.0.0.1",
  "permissions": [
    "activeTab", "storage","tabs"
  ],
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["js/lib/jquery.1.9.0.min.js", "js/content.js"],
    "css": ["css/style.css"]
  }],
  "background":{"scripts":["js/background.js"]},
}

content.js:

window.onload = function() //init
{
  div = document.querySelector("div"); //get the first div in each page for example
  chrome.runtime.sendMessage({firstDiv: div.innerHTML});
  console.log("message sent.");
}

background.js:

chrome.runtime.onMessage.addListener( //receive messages 
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    console.log(request);
  });

This works as expected most of the time, and I see the the first div innerHTML messages that passes from the content scripts. However, On StackOverfow.com for example, I get this output on the background script console:

from a content script:http://stackoverflow.com/
Object {firstDiv: ""}     

Message passes, but it seems the first div is empty. This is obviously false information, because when I use Chrome's devtools and manually type "div" in console with the extension context, I see:

<div id="notify-container"></div>

Why is this happening? Is this a security feature?

Upvotes: 1

Views: 180

Answers (1)

rsanchez
rsanchez

Reputation: 14657

You are getting an empty string because innerHTML returns the HTML syntax describing the element's descendants, and in this case the div has no descendants. If you want to include the parent element in the HTML returned you should use outerHTML instead.

Upvotes: 2

Related Questions