消息传递在chrome扩展中不起作用

Message Passing is not working in chrome extention

本文关键字:不起作用 扩展 chrome 消息传递      更新时间:2023-09-26

我尝试将消息从我的Default_popup.js传递到内容脚本,当它在内容脚本端接收时,然后尝试将数据保存在chrome存储上。但我的代码工作不正常。

此代码已被处理了2-3次。但现在它不起作用了。

manifest.json

{
    "manifest_version": 2,
    "name": "Test",
    "description": "Automated Test Tool.",
    "version": "1.0",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "Default_Popup.html"
    },
    "content_scripts": [{
        "matches":["http://*/*","https://*/*"],
        "js":["myscript.js"]    }
    ],
    "background":{
        "scripts":["background.js"]
    },
    "permissions":[
        "storage",
         "notifications",
         "tabs",
         "http://*/",
         "https://*/"
    ]
}

Popup.js

chrome.tabs.getSelected(null, function (tab) {
    var Jour = {};
    Jour.FromStation = $('#txtFromStation').val();
    Jour.ToStation = $('#txtToStation').val();
    Jour.JourneyDate = $('#datepicker').val();
    chrome.tabs.sendRequest(tab.id, { JourneyDetails: Jour }, function handler(response) {
        alert("Inside Client = " + "Done");
    });
});

myscript.js//内容脚本

window.onload = function () {
    chrome.extension.onRequest.addListener(
        function (request, sender, sendResponse) {
            alert('request.JourneyDetails.FromStation');
            alert(request.JourneyDetails.FromStation);
            var Jour = {};
            Jour.FromStation = request.FromStation;
            Jour.ToStation = request.ToStation;
            Jour.JourneyDate = request.JourneyDate;
            chrome.storage.sync.set({ JourneyDetails: Jour }, function () {
                console.log('Setting Saved')
            });
            //sendResponse({ counter2: "5" });      
       }
    );
}
  1. chrome.tabs.getSelected()已弃用,是否尝试使用chrome.tabs.query()?https://developer.chrome.com/extensions/tabs#method-getSelected
  2. chrome.tabs.sendRequest()chrome.extension.onRequest()已弃用,是否尝试使用chrome.tabs.sendMessage()chrome.runtime.onMessage()?https://developer.chrome.com/extensions/tabs#method-sendRequest,https://developer.chrome.com/extensions/extension#event-onRequest
  3. 是否在Default_Popup.html中包含jQuery?你看到的错误是什么
  4. Default_Popup.html中id为$('#txtFromStation'), $('#txtToStation'), $('#datepicker')的元素吗?如果您可以发布Default_Popup.html的内容,那将很有帮助