【问题标题】:How to access variables from background.js to pop up in chrome extension如何从 background.js 访问变量以在 chrome 扩展中弹出
【发布时间】:2017-09-27 15:55:37
【问题描述】:

在 chrome 扩展中,我正在通过 background.js 创建一个新的 html 页面作为弹出窗口。查看下面的 background.js 代码,

 chrome.contextMenus.create({
title: "share this",
contexts: ["selection"],
onclick: myFunction

});

var test0 = "Testing content Outside the myfunction";

function myFunction(data) {
  var theSelection = data.selectionText;
      console.log(theSelection);

      chrome.tabs.query({'active': true, "lastFocusedWindow":true}, function(tabs) {
              var sourceURL = tabs[0].url;

                                chrome.windows.create({
                  url: chrome.runtime.getURL('redirect.html'), type: 'popup'},
              function(tab)
                            {

                               });
                return record;
            })

    }

我已经完成了给定here 的getbackgroundpage 函数。我可以使用它访问变量 test0 但不能访问 sourceURL (因为它不在窗口范围内)。

通过重定向弹出窗口代码如下,

var bg = chrome.extension.getBackgroundPage();
var sourceURL = bg.sourceURL;
var testvariable = bg.test0;

sourceURL 未定义。

不知道如何将变量定义为全局变量以便在弹出窗口中访问。

有没有更好的方法,我们可以做到吗?

【问题讨论】:

  • 使用消息传递或 chrome.storage.local 或 localStorage 或其他全局变量。
  • 如何使用全局变量选项。非常感谢如果给出语法。
  • test0 是一个全局变量。

标签: google-chrome-extension extension-methods browser-extension


【解决方案1】:

伙计,尝试使用Gogle message passing

前面链接的小例子

背景脚本

 var myFunc = function(){
 //some code
 }
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.messageType == "callSomeFunc") {
            myFunc();
            sendResponse({
                status: "Function myFunc called."
            });
        }
        //use return true for async response
        return true;
    });

内容脚本

  chrome.runtime.sendMessage({
        messageType: "callSomeFunc"
    },    
    function(response) {
        // response contain {status: "Function myFunc called."}
        console.log(response);    
    });

【讨论】:

    猜你喜欢
    • 2013-03-12
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 2014-09-18
    相关资源
    最近更新 更多