【问题标题】:How can I pass data from an injected content script to an iframe?如何将数据从注入的内容脚本传递到 iframe?
【发布时间】:2015-03-01 21:25:29
【问题描述】:

这是我第一次开发 chrome 扩展,老实说,我什至不确定这是否是正确的设计模式。

我的 Chrome 扩展在工具栏中有一个按钮。单击该按钮时,我想将 iframe 直接切换到活动网页中。

我让那部分工作没问题:

manifest.json

{
  "manifest_version":         2,
  "description":              "Inject a complete, premade web page",
  "name":                     "Inject whole web page",
  "version":                  "1",
  "web_accessible_resources": ["html/price-snipe-iframe.html"],
  "permissions": [
    "tabs", "http://*/*", "https://*/*"
  ],
  "background": {
    "scripts": ["js/lib/jquery.min.js", "background.js"]
  },
  "browser_action": {
    "default_icon": {
      "19": "icons/action19x19.png",
      "38": "icons/action38x38.png"
    },
    "default_title": "Price Sniper"
  }
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {

  chrome.tabs.insertCSS(null, {
    file: "css/global.css"
  });
  chrome.tabs.executeScript(tab.id, { file: "js/lib/jquery.min.js" });
  chrome.tabs.executeScript(tab.id, { file: "iframe-injector.js" });

});

iframe-injector.js

var snipeBar = $('#price-snipe-bar');

if (! $('#price-snipe-bar').length) {
  var iFrame  = document.createElement("iframe");
  iFrame.src  = chrome.extension.getURL("html/price-snipe-iframe.html");
  iFrame.id = "price-snipe-bar";
  iFrame.innerHTML = "<h1>GOT IT?</h1>"

  document.body.insertBefore(iFrame, document.body.firstChild);

  $('body').css({ 'margin-top': '43px'});
} else {
  $('#price-snipe-bar').remove();
  $('body').css({ 'margin-top': ''});
}

在这里,我只是查看 iframe 是否存在,如果不存在,我将插入它。

我真正需要做的是从活动或当前标签/页面中取出图像,并将它们注入 iframe。

有没有办法做到这一点,或者有更好的模式?

【问题讨论】:

    标签: javascript iframe google-chrome-extension


    【解决方案1】:

    您在文档中创建一个新的iframe

    它的来源是chrome-extension://...,所以它应该可以完全访问 Chrome API。

    您可以使用该框架脚本中的Messaging 联系您的内容脚本并请求数据。

    唯一棘手的事情是传递正确的选项卡 ID,但您可以通过 passing it to the content script first 来完成,然后在 URL 中创建一个以选项卡 ID 作为参数的框架。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多