Google Chrome扩展消息背景到上下文 [英] google chrome extension messaging background to context
本文介绍了Google Chrome扩展消息背景到上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为Google Chrome编写一个扩展。内容脚本永远不会看到sendNextProfile请求已从后台页面发送。至少,消息接收请求下一个配置文件不会出现在控制台日志中,也不会在后台看到新的请求。
以下是内容脚本中的代码
//send request for first profile
var currentProfile=0;
chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[currentProfile]});
//listen for request to send next profile
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "sendNextProfile") {
console.log("RECEIVED REQUEST FOR NEXT PROFILE");
++currentProfile;
chrome.extension.sendRequest({cmd: "openProfile", url: profileLinks[currentProfile]});
}
});
以下是背景页中的代码
//detect when message tab is closed and request new profile
//var closedTabId=null;
chrome.tabs.onRemoved.addListener(function(tabid, removeInfo) {
console.log("TAB CLOSED "+tabid);
if (tabid==msgTabId) {
chrome.extension.sendRequest({cmd: "sendNextProfile"});
console.log("REQUESTED NEW PROFILE");
}
});
在后台,控制台消息按预期显示,因此看起来请求已发送。那么这段代码是怎么回事?
推荐答案
而不是:
chrome.extension.sendRequest({cmd: "sendNextProfile"});
应该是:
chrome.tabs.sendRequest(tabId, {cmd: "sendNextProfile"});
但是,如果您的选项卡被删除,向该选项卡发送请求就没有意义了,因为它不存在。也许您需要将其发送到其他选项卡?
这篇关于Google Chrome扩展消息背景到上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文