使用chrome扩展在iframe中注入javascript

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

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

我很好奇这是否可以使用chrome扩展来完成?

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

"content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["content_frame.js"], "all_frames": true }], 

通过将all_frames设置为true您将注入/包含content_frame.js javascript文件到顶级文档和所有iframe中。 如果你只需要在iframe中注入javascript而不是在top文档中注入,你可以在你的content_frame.js文件中检查如下:

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