2013-04-26 107 views
0

因此,我試圖將數據從本地存儲的鉻背景頁面發送到內容腳本,然後對數據進行一些操作。之後,我想將其發送回後臺頁面,並更新本地存儲的後臺頁面。這可能嗎。我知道如何將數據從後臺發送到內容腳本,但是如何從內容腳本發送到後臺?chrome消息從背景到內容腳本再到背景

background.html

var background = chrome.extension.getBackgroundPage(); 

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse, getBackResponse) { 
    if (request.extensionSettings === "storage") { 

     // send local storage data {"one": "data", "two": "data"} 
     sendResponse({storageString: background.localStorage.extdata}); 

     // save new data from content script 
     localStorage.setItem("extdata", getBackResponse); 
    } 
}); 

的script.js

chrome.runtime.sendMessage({extensionSettings: "storage"}, function(response) { 
    var json = JSON.parse(response.storageString); 

    console.log(json); 
    // take json object do a few things with data 
    // take data and make new json string, and send it background page 
    sendBack('{"one": "new data", "two": "more new data"}'); 
}); 

回答

2

在這種情況下,你只是想送你去後臺頁面的信息來區分好的。要做到這一點的方法之一是用一個簡單的標識是這樣的:

內容腳本

chrome.runtime.sendMessage({method:"getStorage",extensionSettings:"storage"}, 
function(response) { 
    var json = JSON.parse(response.storageString); 

    console.log(json); 
    // take json object do a few things with data 
    // take data and make new json string, and send it background page 
    // Let's just say that `sendBack` is now defined to be a var 
    // With the info you want to send back 
    var sendBack = {"one": "new data", "two": "more new data"}; 
    chrome.runtime.sendMessage({method:"setStorage", newData:sendBack}); 
}); 

有了這個,我們發送郵件來獲取數據,操縱它的回調,然後將其發送背部。現在來處理它。

背景頁

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) { 
    if(message.method == "getStorage"){ 
    if(message.extensionSettings === "storage") { 
     // send local storage data {"one": "data", "two": "data"} 
     sendResponse({storageString: background.localStorage.extdata}); 
    } 
    } 
    else if(message.method == "setStorage"){ 
    // save new data from content script 
    localStorage.setItem("extdata", message.newData); 
    } 
}); 

這樣我們就可以只通過改變任何你需要將其命名method或值處理多種不同類型的消息。