问题描述
我有一个chrome扩展程序,这个chrome扩展程序的用例如下:
第1部分
- chrome扩展程序有一个弹出页面,其中包含2个div元素和一个按钮
- 单击弹出窗口后,获取当前选项卡的URL会使用chrome.runtime.sendMessage API将其发送到后台脚本
- 后台脚本有一个消息侦听器,它使用cookie进行xhr请求,获取与url相关的数据,然后将其发送回popup.js
- popup.js根据接收到的数据编辑2个div元素
这部分效果很好,但是第二部分有些棘手:
第2部分:
- 如果我们单击弹出窗口中的按钮,则使用在第1部分中获得的一些数据,必须进行一些时间转换
- 此时间转换后,我需要与页面的DOM交互并为此编辑一些元素,我需要将时间转换的结果发送到内容脚本
- 要实现Point-2,作为测试的一部分,我正在使用chrome.tabs.sendMessage API将数据专门发送到选项卡的内容脚本,并希望将其取回,但是在弹出窗口中出现以下错误.js
未经检查的runtime.lastError:无法建立连接。接收端不存在。
请在下面找到我的清单,背景,时区和popup.js(我的内容脚本)代码:
manifest.json
{
"manifest_version": 2,"name" : "Switcher","version": "1.1","browser_action":{
"default_popup":"popup.html"
},"permissions":["tabs","activeTab","cookies","<all_urls>"],"background": {
"scripts": ["background.js"],"persistent": false
}
}
Popup.js
document.addEventListener("DOMContentLoaded",function(event){
var obj = {"active": true,"currentwindow": true}
chrome.tabs.query(obj,function(tab){
chrome.runtime.sendMessage({url: tab[0].url,action: "id_load"},function(response) //Send message to background script with the URL of the tab
{
//Manipulate the popup divs using the response from background script
})
})
var timezone = document.getElementById("change_timezone")
timezone.addEventListener('click',change_timezone_function)
function change_timezone_function()
{
var query_info = {active: true,currentwindow: true}
chrome.tabs.query(query_info,function(tab){
console.log(tab[0].id)
chrome.tabs.sendMessage(tab[0].id,{time: ticket_time},function(response) //Send message to the content script by getting the tab ID
{
console.log(response)
})
})
}
})
background.js
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse)
{
//Do some manipulation,few api calls and send response asynchronously after the api call is successful
return true
})
timezone.js
chrome.runtime.onMessage.addListener(function(request,sendResponse){
var date_time = new Date(request.time.toString())
console.log(request.time)
sendResponse({date_time: request.time})
})
所有答案都指向以下事实,即popup.js可以使用选项卡特定的消息与内容脚本进行交互,但这似乎不起作用,我认为这可能是由于后台中的侦听器,但是从逻辑上讲,没有理由相信,因为我的弹出消息是专门发送到选项卡的内容脚本的。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)