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

时间:2015-12-26 05:41:14

标签: javascript jquery google-chrome google-chrome-extension message-passing

我尝试将消息传递从我的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 个答案:

答案 0 :(得分:1)

  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-sendRequesthttps://developer.chrome.com/extensions/extension#event-onRequest
  3. 你在Default_Popup.html中包含jQuery吗?您看到的错误是什么?
  4. Default_Popup.html中的ID为$('#txtFromStation'), $('#txtToStation'), $('#datepicker')的元素是?如果您可以发布有用的Default_Popup.html内容。