【问题标题】:Access HTML of an cross-origin iframe in a chrome extension content script via jQuery?通过 jQuery 在 chrome 扩展内容脚本中访问跨域 iframe 的 HTML?
【发布时间】: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


【解决方案1】:

所以 - 好消息是您的代码中已经有 "all_frames" : true。你可能想拥有

"matches": [
        "<all_urls>"
      ],

如果您想在所有网页上加载此功能,请在清单中。对于谁是谁的父级——你必须构建一种树。

基本上,您的内容脚本将加载到父框架以及该框架中的 iframe 中。您可以使用referrer property 并通过

获取哪个 URL 加载了哪个页面
window.document.referrer

并且您的 iframe 应该指向您的父框架。我不知道你的限制,但我想你可以弄清楚父页面是什么(或者你可能已经知道了?)所以只需说 页面 A 在 iframe 中加载页面 B .在那个阶段,您的内容脚本都在它们中,因此您可以访问它们。

【讨论】:

  • @ammar075 - 如果它有资格作为答案,我将不胜感激。
猜你喜欢
  • 2011-04-25
  • 2012-07-04
  • 2013-05-20
  • 1970-01-01
  • 2011-11-02
  • 2014-03-04
  • 2011-09-28
相关资源
最近更新 更多