2016-10-01 32 views
0

我正在進行非常簡單的擴展。我的popup.html有一些單選按鈕,代表用戶的一組預定義選項。問題是我的內容腳本的邏輯取決於這些選項。我可以將popup.html中的輸入數據保存在localStorage中嗎?

所以,我的問題是: 讓我們假設我會附上一個腳本來「popup.html」(會議鉻CSP)是聽我的單選按鈕選擇的任何變化,一旦它發生不成才等。 localstorage.setItem(key,value)?我的內容腳本能夠在適當的時候從本地存儲中獲取此值嗎?

+0

爲什麼你不能那樣做? – Fralec

+0

@Fralec我對此很新。這就是我問的原因。我應該調用'chrome.storage.localStorage.setItem()'? – 52hertz

+0

您似乎對['Window.localStorage'](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)和['chrome.storage']之間的區別感到困惑。 ](https://developer.chrome.com/extensions/storage)請參閱:[window.localStorage vs chrome.storage.local](http://stackoverflow.com/questions/24279495/window-localstorage-vs-chrome-存儲本地)。如果有興趣,[這個答案](http://stackoverflow.com/a/39236352/3773011)有一個示例popup&選項頁面,它將數據存儲到'chrome.storage.local',並且它已經在Chrome和Firefox瀏覽器。 – Makyen

回答

1

當然,你可以做到這一點。這裏有兩個例子:

chrome.storage.local.set({'value': theValue}, function() { 
    // Notify that we saved. 
    message('Settings saved'); 
}); 

chrome.storage.local.get('value', function(obj) { 
    //Notify that we get the value. 
    message('Value is ' + obj.value); 
}); 

或者您可以使用同步存儲:

chrome.storage.sync.set({'value': theValue}, function() { 
    // Notify that we saved. 
    message('Settings saved'); 
}); 

chrome.storage.sync.get('value', function(obj) { 
    //Notify that we get the value. 
    message('Value is ' + obj.value); 
}); 

這裏是the documentation

chrome.storagewindow.localStorage之間的區別是,您可以在每個最近的瀏覽器上使用window.localStorage。也在網站上。存儲的對象將被存儲直到用戶關閉瀏覽器。

您正在構建Chrome擴展程序,因此我建議您使用爲此製作的API。

+0

考慮到['Window.localStorage'](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)的具體問題,您應該解決該API和['chrome.storage'](https://developer.chrome.com/extensions/storage)。 – Makyen

+0

再次。只是爲了讓我做對了。我創建了一個popup.html。以'

相關問題