gpt4 book ai didi

javascript - Chrome 扩展 - 修改消息事件的弹出页面

转载 作者:搜寻专家 更新时间:2023-11-01 05:13:01 24 4
gpt4 key购买 nike

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

我试过:

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

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

最佳答案

弹出窗口虽然是扩展页面,但不是背景页面。它只有在打开时才能访问。因此,根据其他信息更改弹出页面的最佳方法是从弹出窗口本身启动消息。我认为您正在使用内容脚本在页面上获取某种信息,然后根据该信息更改弹出窗口。您可以准备数据并在内容脚本本身中有一个 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 .

关于javascript - Chrome 扩展 - 修改消息事件的弹出页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com