Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject CSS and Javascript into an iframe loaded in a chrome extension

I have an iframe in my chrome extension that loads a website, I'd like to inject CSS and Javascript into the website but only when its loaded in my extensions iframe (so it doesn't get affected when the user browses to the site normally).

I was surprised that Chrome extensions have cross-domain security policies applied to them when they try to access the internals of an iframe even though they can make cross-domain XHR requests.

Is there an easy way to do this? I though I might be able to do it using executeScript but it requires a tab ID.

like image 607
Sean Bannister Avatar asked Nov 17 '11 05:11

Sean Bannister


1 Answers

The only way to know if you are in an ifrmae is the window is not the top.

if (window == top) {
  // Not in iframe
}
else {
  // In an iframe
}

You can only do that for content scripts, not for stylesheets. What I usually do is within the content script, I check if it isn't in the top window, and then continue the script, otherwise I just end it.

Recap

  1. Inject the Content Script for that URL
  2. In the content script, check if the window property, if (window != top) { loadContentScript() }
  3. Create the CSS in the JavaScript if you are too worried about it affecting. You shouldn't though if you use unique ids.

Hope that helped, I do that for a few extensions of mine.

like image 93
Mohamed Mansour Avatar answered Oct 25 '22 01:10

Mohamed Mansour