25

if I write a Chrome extension that runs a snippet of JS on a page, will it also run in any iframes I create? If so, does this apply for iframes created by Javascript after the DOM has loaded?

Thanks!

Garen Checkley
  • 5,512
  • 6
  • 22
  • 24

2 Answers2

50

Yes, a Chrome Extension "content script" can run in all iframes (that are initially in the HTML when the page is loaded). In order to have the content script run in all frames you need to configure it to do so in the Chrome Extension manifest.json using the all_frames property:

http://code.google.com/chrome/extensions/content_scripts.html

{
  "name": "My extension",
  ...
  "content_scripts": [
    {
      "matches": ["http://www.google.com/*"],
      "css": ["mystyles.css"],
      "js": ["jquery.js", "myscript.js"],
      "all_frames": true
    }
  ],
  ...
}

No, the content scripts will NOT execute in the iframes loaded dynamically via JavaScript in the page.

Adam Ayres
  • 8,732
  • 1
  • 32
  • 25
  • Is there a way to make the content script execute on the dynamically loaded JS too? Or is it just not possible? – Honoki Apr 27 '13 at 20:12
  • @Honoki I do not believe there is any way to get the Chrome extension to add JS to iframes dynamically added in the JavaScript after the page has loaded. However, if you control the contents of the iframe then you could do whatever you wanted. What are you trying to load in the iframe? Maybe there is a Web API that can get you want you need - if not Yahoo pipes + YQL can be handy for grabbing content off of other sites that do not have a nice Web/REST API. – Adam Ayres May 01 '13 at 04:49
  • 4
    It seems from my experimenting that contentscripts *do* get executed in newly created iframes ... also note that it is running separate copies of your contentscript.js, once per each iframe (though they could theoretically communicate with each other through message passing), and once for the main document... – rogerdpack Oct 28 '16 at 18:24
  • But the css's specified in the manifest do not permeate into the iframe... – Nathan B May 24 '21 at 07:58
5

Content scripts defined in the manifest (with "all_frames": true) will run on newly created iframes. What matters is that a new navigation starts for every frame, and content scripts are scheduled to be injected at that point.

In contrast, if you dynamically inject code with chrome.tabs.executeScript(), then it will only be injected in the frames present at the time you call it. You'd need some mechanism to detect new frames (Mutation observers? webNavigation API?) if you want to keep up with them.

Xan
  • 74,770
  • 16
  • 179
  • 206