微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从弹出窗口到内容脚本的消息不起作用

如何解决从弹出窗口到内容脚本的消息不起作用

我有一个chrome扩展程序,这个chrome扩展程序的用例如下:

第1部分

  1. chrome扩展程序有一个弹出页面,其中包含2个div元素和一个按钮
  2. 单击弹出窗口后,获取当前选项卡的URL会使用chrome.runtime.sendMessage API将其发送到后台脚本
  3. 后台脚本有一个消息侦听器,它使用cookie进行xhr请求,获取与url相关的数据,然后将其发送回popup.js
  4. popup.js根据接收到的数据编辑2个div元素

这部分效果很好,但是第二部分有些棘手:

第2部分:

  1. 如果我们单击弹出窗口中的按钮,则使用在第1部分中获得的一些数据,必须进行一些时间转换
  2. 此时间转换后,我需要与页面的DOM交互并为此编辑一些元素,我需要将时间转换的结果发送到内容脚本
  3. 要实现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 举报,一经查实,本站将立刻删除。