【发布时间】:2019-05-19 22:46:01
【问题描述】:
我正在开发一个 chrome 扩展程序,用于收集网站上投放的展示广告以进行研究。我正在尝试通过 jquery 访问广告 html,如下所示:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
if(request.todo == "CaptureAds"){
frames = $('iframe')
for(var iter=0;iter<frames.length;iter++){
console.log('==================IFRAME====================')
console.log('A')
console.log(frames[iter])
console.log('B')
console.log(frames[iter].contentDocument)
console.log('C')
console.log(frames[iter].src)
}
}
});
这给了我以下结果:
An cross-origin iframe that I can print but cannot access to the html of
Two normal iframes that I can print and have access to their html as well
我在 stackoverflow 上查找了多个问题,它们导致了 postMessage 方法。就我而言,我没有对 iframe 的编辑访问权限,因此我无法按照这些解决方案中的建议在两个 iframe 之间进行通信。有人可以建议一种在这种情况下绕过同源策略而不会弄乱浏览器设置的方法。
这是我的清单:
{
"manifest_version": 2,
"name": "xyz",
"version": "1.0",
"description": "abc",
"icons": {
"16": "images/get_started16.png",
"32": "images/get_started32.png",
"48": "images/get_started48.png",
"128": "images/get_started128.png"
},
"page_action": {
"default_icon": "images/get_started16.png",
"default_popup" : "popup.html",
"default_title": "example"
},
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["https://www.example.com/*"],
"js": ["content.js", "jquery-3.3.1.min.js"],
"all_frames": true
}
],
"permissions": ["activeTab","https://www.example.com/*","webNavigation"]
}
【问题讨论】:
-
你能分享你的扩展清单吗?
-
广义地说,解决方案是有一个内容脚本,你的清单告诉它加载到每个页面上,包括那些在框架中的页面。由于内容脚本可以访问它加载到的页面的 DOM,因此您可以通过与内容脚本交换消息来访问 iframe DOM。
-
添加了清单
-
@Utkanos 我如何使它在所有帧中加载相同的内容脚本?另外我如何在不同框架的范围内唯一标识相同的内容脚本?
-
你可以谷歌如何在所有框架中添加内容脚本——谷歌有这方面的文档。至于如何在不同的上下文中识别相同的内容脚本,这取决于您传递的消息。给每个人一个 ID,并且只有内容脚本的某些实例响应,具体取决于 ID 是什么。
标签: javascript jquery google-chrome