Paul Aston
Paul Aston

Reputation: 135

Get variables from webpage with Chrome Extension - localstorage?

I am building a Chrome extension to be used with a mapping page. The user logs into the map, and a lot of variables are passed from a database into the map.

When the extension is opened is there a way to pass these variables into it? I was thinking about LocalStorage:

As a test I tried this in the map page HTML

if (typeof(Storage)!=="undefined") {
localStorage.setItem("firstname", "hello");
localStorage.setItem("lastname", "world");
}  

And then in the extension content I just tried

alert('My name is ' + localStorage.getItem("firstname") + ' ' +
localStorage.getItem("lastname"));

I can see the variables under localstorage in the map page developer tools. But I see a different set in the extension.

It seems as if the extension can't read these. Is there a way I can send these over, or do I need a different method?

Upvotes: 1

Views: 1029

Answers (1)

Dominic Green
Dominic Green

Reputation: 10258

I think what you want is message passing in chrome. See this article https://developer.chrome.com/extensions/messaging.html

The basics would be something like this

chrome.extension.getLocal({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

.

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocal"){
      sendResponse({data: localStorage[request.key]});
    }else{
      sendResponse({}); }
});

You could also look into using chrome storage rather than local storage http://developer.chrome.com/extensions/storage.html

Upvotes: 1

Related Questions