Chrome扩展程序 - 修改邮件事件的弹出页面

emt*_*mte 4 javascript google-chrome-extension

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

我试过了:

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

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

Bea*_*ist 8

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

内容脚本

...
//assume that you already have the info you want stored in 'info'

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  sendResponse(info);
});
Run Code Online (Sandbox Code Playgroud)

弹出

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
  });
});
Run Code Online (Sandbox Code Playgroud)

根据要求,它使用后台页面作为中介:

内容脚本

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

背景页面

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);
});
Run Code Online (Sandbox Code Playgroud)

弹出

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

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