心魅 - cocoromi -

半角スペース時々全角

localStorageをつかってエクステンションの設定を管理する

エクステンションではlocalStorageを使ってデータを保存することができます。
簡単なサンプルは以下のページに載っています。


Options
http://code.google.com/chrome/extensions/options.html


コンテントスクリプト以外のエクステンション要素からはJavascriptのlocalStorageオブジェクトにアクセスするだけで読み書きが行えます。
※background_page や options_page他
コンテントスクリプトからはメッセージングAPIを使ってアクセスするためのプロキシを実装する必要があります。

options_pageでユーザIDとパスワードを保存するサンプル

上述したページのサンプルとほとんど変わらないので、マニフェストの設定は省きます。

オプションページが開かれると、まずユーザIDとパスワードをlocalStorageから呼び出してフォームに設定します。
※保存されてなければ空文字

ボタンがクリックされると、フォームに入力されている値をlocalStorageに保存します。

<html>
<head><title>store value example</title></head>
<script src="options.js"></script>
<body onload="restore_options()">

User ID :<input id="userId" type="text"></input>    <br>
Password:<input id="passwd" type="password"></input><br>

<br>
<button onclick="save_options()">Save</button>
<div id="status"></div>
</body>
</html>
function save_options() {
    //フォームの入力内容をlocalStorageに保存
    localStorage["userId"] = document.getElementById("userId").value ;
    localStorage["passwd"] = document.getElementById("passwd").value ;

    //おまけ
    var status = document.getElementById("status");
    status.innerHTML = "Options Saved.";
    setTimeout(function() { status.innerHTML = ""; }, 750);
}

function restore_options() {
    //既に保存されていればフォームにその値を設定
    document.getElementById("userId").value = ( localStorage["userId"] || "" );
    document.getElementById("passwd").value = ( localStorage["passwd"] || "" );
}

コンテントスクリプトからlocalStorageにアクセスするサンプル

まずはコンテントスクリプトの通信相手であるbackground_pageを用意します

<html>
    <head>
        <script src="background.js"></script>
    </head>
    <body>
    </body>
</html>
//background.js
window.onload = init

//趣味
var CMD = {
    setValue  : setValue ,
    getValue  : getValue ,
    getValues : getValues 
} ;

function init() {
    chrome.extension.onRequest.addListener( function ( message , sender , sendResponse) {
        //趣味
        var retVal = (CMD[ message.action ]||function(){}).apply( CMD , message.args ); 

        //関数の実行結果をレスポンスの引数として返す
        //sendResponse.apply( null , retVal )とかの方が綺麗かも?
        sendResponse( { values : retVal } );
    } ) ;
}

function getValues( list ){
    for( var i in list ){
        list[i] = getValue( i , list[i] );
    }

    return list ;
}

function getValue( name , def ){
    if( !localStorage[ name ] ){
        localStorage[ name ] = def;
    }
    return localStorage[name];
}

function setValue( name , value ){
    localStorage[ name , value ];
}

これに対してコンテントスクリプトから以下のようにアクセスします。

var option = null ;

//真っ先に必要なデータを裏から受け取る
chrome.extension.sendRequest( { 
        //localStorageからuserIdとpasswdを読み込むお願いをする
        action : "getValues" , 
        args   : [{ 
            "userId" : "" , 
            "passwd" : ""
        }]
    } , function( response ){
        option = response.values ;

        //データの準備が整ったらコンテントスクリプトを初期化
        init();
    }
);

function init(){
    var userId = option["userId"] ;
    var passwd = option["passwd"] ;
    alert( userId + " | " + passwd );
}

まとめ

localStorageを使って簡単にデータの保存ができる。
エクステンションの設定なんかもどんどん保存できる。
コンテントスクリプトからのアクセスには絶対にコールバックが必要になるので、
localStorageを使う場合はそれを念頭に設計した方がいい。