Jhon Casey
Jhon Casey

Reputation: 11

content script within dynamic html iframe and manipulating chrome functions

I've been developing a chrome extension which fetches html content from my server, creates an iframe within a page and injects the html inside. Thus, there isn't "src" attribute and because of that, my content script isn't being injected.

manifest.js:

"background": { "scripts":["background.js"] },
"content_scripts":
 [
  {"js": ["toolbar.js"], "matches": ["http://*/*"]},
  {"js": ["frame.js"], "matches": ["<all_urls>"], "all_frames":true}
 ],
"web_accessible_resources": [ "loader.gif","frame.js" ],
"permissions": [ "browsingData", "history", "storage", "tabs", "management", "<all_urls>" ]

background.js:

chrome.extension.onMessage.addListener(function(details)
{
  if(details.message.sendBack)
  {
    chrome.tabs.sendMessage(details.sender.tab.id,details.message.data);
  }
});

frame.js:

some function...
if...()
{
  chrome.extension.sendMessage({ sendBack: true,data: data });
}

toolbar.js:

function setContent(data)
{
  iframe.contentDocument.open('text/html');
  iframe.contentDocument.write(data);
  iframe.contentDocument.close();
}

Now, the iframe hosts a toolbar in which there are browser-related functions, such as clearing history, etc. HTML-speaking, there is an anchor which onclick should post a message to the extension, sending "clearHistory" command. These function requires a chrome-extension access to chrome.history and chrome.management, so I need to deliver messages between the html objects and parent extension.

Problem is iframe doesn't get the frame.js script injected, even when its src is set to some local file. Maybe I'm doing something wrong, yet I can't find a way to inject the script. I'm not even sure injecting the script will allow such mechanism.

I tried to get the relative url of the script (chrome.tab.getURL) and the script was actually injected, yet console.log(chrome) didn't show the extension object or any method I could use (I believe it's due to the manual injection)

What do you think?

Upvotes: 0

Views: 1651

Answers (1)

Brock Adams
Brock Adams

Reputation: 93483

The contents of the iframe are coming from your server, right? If so, then don't use iframe.contentDocument to write the frame. Have your server serve the iframe up directly. EG:

$("body").append ('<iframe src="http://YOUR_SERVER.com/YOUR_PATH?urlParams=ifAny" id="extIframe1"></iframe>');

Chrome extensions don't work well on JS-generated iframes.

Then adjust the manifest line to something like:

{"js": ["frame.js"], "matches": ["http://YOUR_SERVER.com/YOUR_PATH*"], "all_frames":true}

Upvotes: 1

Related Questions