开发者

Chrome extension : access local storage more than once in content script

I know how to access localstorage in content script, but only one time. I access it via sendRequest, but when I try to开发者_如何学运维 use this method in an event function, the jvascript file doesn't even load. Is it possible to access to the options many times, like whenever the onclick event is fired ? I looked on the google code website and found something to create a connection between content script and background using chrome.extension.connect(). Do i need to use that ?

Thanks !


Actually you can use sendRequest as many times as you can, but if you want to do it in another way you can open a long-lived channel (or what I call, "message tunnel") between content script and background page to communicate.

In your content script, you can use
var port = chrome.extension.connect({name: "myChannel"}); to open up a channel.

Then you can use
port.postMessage({message: "This is a message."});
to send a new message to the background page.

port.onMessage.addListener(function(msg) { }) listens to a new message.

In your background page,

chrome.extension.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
        if(port=="myChannel"){
            console.log(msg+" from port "+port)        //Gives you the message
        }
    })
})

listens to a new message in a specific port.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜