Chrome扩展程序内容脚本和iframe

22

我正在尝试为Google Chrome制作一个扩展程序,它可以执行以下操作:

在加载www.example.com时运行。 example.com有一个内嵌框架到另一个站点,我需要访问此框架中的链接(这是rapidshare,我需要获取下载链接)。

到目前为止都很好,但是...

然后,我需要扩展程序将链接URL通知给example.com以进行进一步处理。

有任何想法或方向吗?

我已经阅读了http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication,但无法使其工作...


这个部分重复的问题中解决了iframe注入部分。 - Dan Dascalescu
3个回答

56

您需要注入2个内容脚本:

"content_scripts": [
    {
      "matches": ["http://www.example.com/*"],
      "js": ["example.js"]
    },{
      "matches": ["http://www.rapidshare.com/*"],
      "all_frames": true,
      "js": ["rapidshare.js"]
    }
]

为了将链接从一个脚本传输到另一个脚本,您需要通过后台页面进行通信:

rapidshare.js:

chrome.runtime.sendMessage({url: "link"});

background.js:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    chrome.tabs.sendMessage(sender.tab.id, request);
    sendResponse({});
});

example.js:

chrome.runtime.onRequest.addListener(function(request, sender, sendResponse) {
    console.log("received url:", request.url);
    sendResponse({});
});

谢谢Serg,我现在没有时间测试它,但我会告诉你结果的!再次感谢。 - analogic.al
3
非常感谢你指出可以通过matches属性将不同的脚本加载到不同的页面中! - snapfractalpop
all_frames是做什么用的? - Alexander Mills
all_frames 表示 - 匹配适用于 iFrame 和顶层框架。 - Confused Vorlon

3

0

v3:serg的答案,对我有用

"manifest_version": 3,
"content_scripts": [
    {
      "matches": ["http://www.rapidshare.com/*"],
      "all_frames": true,
      "js": ["insideIframe-content.js"]
    }
]

background.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log(url)
})

insideIframe-content.js:

chrome.runtime.sendMessage(url)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接