【问题标题】:can't access content of iframe injected via google chrome content script using jquery无法使用 jquery 访问通过 google chrome 内容脚本注入的 iframe 的内容
【发布时间】: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();,但无济于事

【问题讨论】:

    标签: javascript jquery google-chrome iframe google-chrome-extension


    【解决方案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 做类似的事情。 如果您需要更多帮助,请告诉我。我在我的扩展中广泛使用了这种技术。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-04
      • 2019-05-19
      • 2011-04-25
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      相关资源
      最近更新 更多