dxlliv
dxlliv

Reputation: 482

Store variable in Chrome Extension (domain 1), but I need it in remote domain (domain 2)

I'm trying to develop a Chrome Extension. In the box extension I allow users to store a variable (like a URL). Then, in the page when the script is active, I have to retreive this value.

Example

Chrome Extension:

localStorage.setItem("url", $("#url").val());

Domain.net (like facebook.com)

var my_url = localStorage.getItem("url");

BUT localStorage doesn't allow cross domain. Don't reply me saying to use GlobalStorage, is deprecated.

Upvotes: 0

Views: 1417

Answers (2)

BeardFist
BeardFist

Reputation: 8201

You can just use the storage API and combine it with message passing. You didn't mention where it is you are saving the value so I am going to assume it is in a popup or something like that. For example:

Popup.js

//Let's define urlData to be the url you obtained from the user
chrome.storage.local.set({'urlData':urlData});

You then said that you needed it in the page so if you inject a content script into that page you can get the value like this:

Content Script

chrome.runtime.sendMessage({method:'getUrl'},function(urlData){
  //do whatever you want with the urlData in here. I will just log it
  console.log(urlData);
});

Background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  if(message.method == "getUrl"){
    chrome.storage.local.get('urlData',function(items){
      sendResponse(items.urlData);
    });
  }
});

Upvotes: 1

dandavis
dandavis

Reputation: 16726

you have to save the data to localStorage in the domain where it will be fetched. it sounds like you control that domain, so you can create a proxy using a simple HTML file on that domain, call it saver.html:

<html><script>
   localStrorage.url=decodeURIComponent(location.hash.slice(1));
</script></html>

to save from the other site/extension, you create a new iframe that points to that html file, concatenating the data as the hash segment of the url:

var theValue="this will be saved as 'url' in localStorage ",
 fr=document.createElement("iframe");
 fr.style.display='none';
 fr.src="http://mysite.com/saver.html#"+encodeURIComponent(theValue);
 document.body.appendChild(fr);

in this fashion, the data is passed to the correct domain and saved to localStorage.

if needed, you can use top.sendMessage() in the proxy html page to signal to your app that the data has been written to the remote localStorage.

Upvotes: 0

Related Questions