无法使用 jquery 访问通过 google chrome 内容脚本注入的 iframe 的内容

Posted

技术标签:

【中文标题】无法使用 jquery 访问通过 google chrome 内容脚本注入的 iframe 的内容【英文标题】:can't access content of iframe injected via google chrome content script using jquery 【发布时间】:2011-11-22 12:10:17 【问题描述】:

所以我通过将内容脚本注入正文来创建这个 chrome 扩展:

这是我的javascript

test.js:

$(document).ready(function()
   Url = chrome.extension.getURL('etc.html');
   link = '<iframe src="' + Url + '" id="frame" scrolling="no" frameborder="0px"></iframe>';
   $('body').prepend(link);
   alert($('.test').html());   
);

这是 etc.html 的内容,应该放到 iframe 中

等.html:

<div class="test">An html</div>

这是我的 manifest.json

manifest.json:


   "content_scripts": [ 
      "all_frames": true,
      "js": [ "js/jquery.js", "js/test.js" ],
      "matches": [ "http://*/*", "https://*/*" ],
      "run_at": "document_end"
    ],
   "description": "Testing",
   "name": "test",
   "permissions": [ "tabs", "http://*/*", "https://*/*", "notifications", "management", "unlimitedStorage", "bookmarks", "contextMenus", "cookies", "geolocation", "history", "idle" ],
   "version": "2.0.0.53"

iframe成功插入body,出现iframe内容,通过chrome inspector看到...

但是当 js 运行 alert($('.test').html()); 行时,它返回 null 而不是返回 html....在开发此类扩展时,我究竟如何访问 iframe 中的内容

我也试过$('#frame').contents().find('.test').html();,但无济于事

【问题讨论】:

【参考方案1】:

我很确定你不能这样做。 现在我在网上找不到任何支持这一点的东西,但我记得有这个问题。我认为这样做的原因是其他脚本和扩展不会与您的 etc.html 混淆。

您可以做的是让 etc.html 中的 javascript 访问并修改其 DOM。如果您需要它与注入 iframe 的内容脚本进行通信,您可以通过后台页面传递消息来实现:http://code.google.com/chrome/extensions/messaging.html

例如,您可以通过简单的一次性请求来做到这一点:

等.html

chrome.extension.sendRequest(msg)

背景.html

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
    chrome.tabs.sendRequest(sender.tab.id, request);
);

contentscript.js

chrome.extension.onRequest.addListener(function(req, sender, sendResponse) 
    //do stuff

你可以用 postMessage 和 onMessage 做类似的事情。 如果您需要更多帮助,请告诉我。我在我的扩展中广泛使用了这种技术。

【讨论】:

以上是关于无法使用 jquery 访问通过 google chrome 内容脚本注入的 iframe 的内容的主要内容,如果未能解决你的问题,请参考以下文章

使用Google的CDN JQuery库(摘录)

无法通过 Google Cloud VM 的外部 IP 访问 nginx 容器

如何在 Google Chrome 中使用 iframe 查看包含 JQuery 的网页

通过 jQuery + Ajax 将带有 Google reCaptcha v2 令牌的图像文件发送到 PHP

Google无法访问,修改hosts文件

无法通过 jQuery 访问 iFrame 的类的高度