0

我嘗試從我的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" });  
     } 
    ); 
} 
+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. Defaultpopup.html中的元素是否帶有ID $('#txtFromStation'), $('#txtToStation'), $('#datepicker')?如果你可以發佈Default_Popup.html的內容,這將是有益的。