将变量从Chrome扩展程序传递到已打开的标签

时间:2017-05-23 10:21:17

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

在我的Google Chrome扩展程序用户点击链接,而不是必须自动登录页面。
流程必须是这样的:用户点击GC扩展中的链接,脚本将获取所有必需的参数,然后发送到新打开的选项卡。
我的脚本必须插入传递的参数并进行一些操作 但我不明白,如何将变量从GC扩展脚本传递到新打开的选项卡?
这是我的manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
 "content_scripts": [
    {
    "js": [ "window/content.js"],
    "matches": [
      "https://steamcommunity.com/login/home/?goto=",
      "http://steamcommunity.com/*",
      "https://steamcommunity.com/*"
    ]
   }
 ],
 "background": {
   "scripts": [
     "./scripts/back.js"
    ]
  },
 "web_accessible_resources": [
   "popup.js",
   "window/content.js"
 ],
"permissions": [
    "activeTab",
    "tabs",
    "<all_urls>",
    "cookies",
    "declarativeContent"
 ]


到目前为止,我已尝试在main.js中使用它:

chrome.tabs.executeScript(
   tab1.id,
      {code: "var test =" + test
       allFrames: true
      },
      {file: "../popup.js"}, )
    })

但是当点击执行时,脚本打开新标签,并执行我写的所有内容,但看不到变量'test'。

1 个答案:

答案 0 :(得分:0)

这不是一件难事,只是一件棘手的事情:你需要从内容脚本中附加一个注入代码。

考虑这个例子:

<强>的manifest.json

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0.0",

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_end",
      "all_frames":false
    }
  ],

  "web_accessible_resources": [
    "inject.js"
  ]
}

<强> content.js

var script = document.createElement('script'); 

script.src = chrome.extension.getURL('inject.js');
script.onload = function() {
    window.postMessage({ type: "FROM_MY_EXTENSIONS", value: "123" }, "*");
}

document.body.appendChild(script);

<强> inject.js

window.addEventListener("message", function(event) {
    if(event.data.type === 'FROM_MY_EXTENSIONS') {
        window._test = event.data.value;
        console.log('_test:', _test);
    }
}, false);

此扩展将在任何带有内容脚本消息值的选项卡中创建新的_test变量。