使用chrome扩展在iframe中注入javascript

cod*_*iot 24 javascript iframe jquery google-chrome google-chrome-extension

关于将javascript注入文档页面有很多问题/答案.我真正想做的是在文档中的iframe中注入javascript.

要明确的是,iframe不属于与文档相同的域.我已经通过控制台尝试了它(不是通过扩展)但是无法这样做.

我很好奇这是否可以使用chrome-extension完成?

Igo*_*mić 49

是的,您可以在manifest.json中使用content_scripts属性,如下所示:

"content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content_frame.js"],
    "all_frames": true
}],
Run Code Online (Sandbox Code Playgroud)

通过设置all_frames,true您将注入/包含content_frame.jsjavascript文件到顶部文档和所有iframe.如果您只需要在iframe中注入javascript但不在顶层文档中注入,则可以在文件中检查content_frame.js如下:

if (parent === top) {
    // here you can put your code that will run only inside iframe
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用include_globs和exclude_globs定位特定的帧,而不用在脚本中执行if语句:https://developer.chrome.com/extensions/content_scripts#include_globs (2认同)