【问题标题】:Chrome extension - modify popup page on message eventChrome 扩展 - 修改消息事件的弹出页面
【发布时间】:2013-03-15 15:09:18
【问题描述】:

您好,我有带有内容脚本的 chrome 扩展,可将消息事件发送到后台页面 我想修改消息事件的弹出背景页面。背景页面最初是空白的

我试过了:

chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
   console.log('message received');
   chrome.extension.getBackgroundPage().document.innerHTML = 'hello world';
}

但是当我点击扩展图标时,它仍然是空白的。你能帮我吗? 我可以在控制台中看到该消息已收到。

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    弹出窗口虽然是扩展页面,但不是背景页面。只有在打开时才能访问。因此,根据其他信息更改弹出页面的最佳方法是从弹出窗口本身启动消息。我认为您正在使用内容脚本在页面上获取某种信息,然后根据该信息更改弹出窗口。您可以准备数据并在内容脚本本身中有一个onMessage 侦听器,或者您可以将信息传递到后台页面并从弹出窗口中请求它。第一个例子是:

    内容脚本

    ...
    //assume that you already have the info you want stored in 'info'
    
    chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
      sendResponse(info);
    });
    

    弹出窗口

    chrome.tabs.query({'active': true,'currentWindow':true},function(tab){
      chrome.tabs.sendMessage(tab[0].id,"stuff", function(response){
        //assuming that info was html markup then you could do
        document.body.innerhtml = response;
        //I personally wouldn't do it like this but you get the idea
      });
    });
    

    按照这里的要求,它使用背景页面作为中介:

    内容脚本

    // same assumption that info is already defined as the info you want
    chrome.runtime.sendMessage({'method':'setInfo','info':info});
    

    背景页面

    var info;
    chrome.runtime.onMessage(function(message,sender,sendResponse){
      // When we get a message from the content script
      if(message.method == 'setInfo')
        info = message.info;
      // When we get a message from the popup
      else if(message.method == 'getInfo')
        sendResponse(info);
    });
    

    弹出窗口

    chrome.runtime.sendMessage({'method':'getInfo'},function(response){
      //response is now the info collected by the content script.
      console.log(response);
    });
    

    当然,您可以以比简单的全局变量更好的方式将信息存储在后台页面中。一种好方法是使用storage API

    【讨论】:

    • 感谢您的回复。我去试试
    • @BeardFist 能否提供第二种情况的示例。
    • @RyanGrush 我添加了你想要的示例。
    • @BeardFist 感谢您的回复,manifest_version 缺少文档:2. 也许存储 API 或 localstorage 是要走的路。这是我在示例 contentscript.js Uncaught ReferenceError: info is not defined ... background.js Uncaught TypeError: Property 'onMessage' of object #<Object> is not a function ... popup.js 中看到的错误消息 Port error: Could not establish connection. Receiving end does not exist.
    • @RyanGrush 如果您想开始自己的问题,我可以提供更好的答案,当您确保发布您的代码时。
    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2016-07-11
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 2013-02-07
    • 1970-01-01
    相关资源
    最近更新 更多