2016-08-04 34 views
0

我是擴展開發的新手。現在我正在測試使用附加SDK開發的Firefox擴展。我想使用HTM5 localstorage來存儲我的擴展中的一個後臺腳本的某些內容,這些腳本將從相同擴展的不同後臺腳本中獲取。 npm(節點數據包管理器)已經被使用,所以問題是我不能使用瀏覽器localStorage對象,我得到了ReferenceError: localStorage is not defined如何使用npm的瀏覽器擴展使用node-localstorage

通過沖浪我瞭解了node-localstorage。我遵循 https://www.npmjs.com/package/node-localstorage的說明。但是,當我測試我的分機在上面的鏈接給定的代碼,我得到一個錯誤:

Message: Module `localStorage.js` is not found at resource://gre/modules/commonjs/localStorage.js 

Stack: 
[email protected]://xxx-at-xyz-dot-com/scripts/Somescript.js:3:23 
@resource://xxx-at-xyz-dot-com/index.js:6:11 
[email protected]://gre/modules/commonjs/sdk/addon/runner.js:147:19 
startup/</<@resource://gre/modules/commonjs/sdk/addon/runner.js:87:9 
[email protected]://gre/modules/Promise-backend.js:933:23 
[email protected]://gre/modules/Promise-backend.js:812:7 
this.PromiseWalker.scheduleWalkerLoop/<@resource://gre/modules/Promise-backend.j s:746:1 – 

這裏是我是如何試圖使用localStorage的近似值:

//Somescript.js (background script) 

module.exports = function() { 
    this.watchTab = function (tabId, port, url) { 
     //some code 
     localStorage.setItem("key","value"); 
     // some code 
    } 
} 

localStorage.setItem("key","value")引發錯誤ReferenceError: localStorage is not defined.這是我無法使用localStorage的原因。

+0

最初的問題是你爲什麼使用node-localStorage而不是HTML5 localStorage?你能否提供關於錯誤的更多細節? –

+0

我嘗試使用HTML5的localStorage但我收到問題是RefernceError:當我使用功能storageAvailable(類型){ \t嘗試{ \t \t變種存儲=窗口[型]是沒有定義窗口, \t \t \t X =' __storage_test__'; \t \t storage.setItem(x,x); \t \t storage.removeItem(x); \t \t return true; \t} \t catch(e){ \t \t return false; \t} } – wittyrandhir

+0

窗口對象在node.js環境中不可用。同樣localStorage不可用。 – wittyrandhir

回答

1

使用Firefox Add-on SDK時,應該嚴格偏向於使用High Level APIs。如果那些不做你想要的,請看Low-Level APIs。只有在上述任何一項都不適合您的需求時才應該探索其他選擇。這些API存在的原因之一是允許您編寫附加組件,而不必擔心在Firefox開發和更改時必須花費大量精力維護代碼。

假設你的問題真的是「我怎樣才能從我的附加SDK擴展中將數據存儲到某種類型的本地存儲?」,那麼你應該至少考慮simple-storage API,它是Add的標準部分-on SDK。

假設你正在使用類似什麼是你的代碼有問題,下面應該工作:

//Somescript.js (background script) 
var simpleStorage= require("sdk/simple-storage"); //Usable elsewhere in your code. 
module.exports = function() { 
    this.watchTab = function (tabId, port, url) { 
     //some code 
     simpleStorage.storage["key"] = "value"; 
     // some code 
    } 
} 

注:您的代碼並沒有說清楚,如果keyvalue應該考慮的變量或字符串文字。

請注意,如果您使用jpm run來開發和測試附件,則需要使用specific profile以使存儲在多次運行中保留。您可以使用--profile and -nocopy options to jpm來做到這一點。

相關問題