Reputation: 21
I wrote a simple JS script to create an object that permit the inizialization of only one instance. If the object is already inizialized it return is without recreate it again.
This is my: myobj.js
var Singleton = {
initialized : null,
init: function(){
console.log("new obj...");
this.initialized = {
'status' : 'initialized'
}
},
getInstance : function(){
if (!this.initialized) this.init();
return this.initialized;
}
}
Then I have create a test.html page to test this script:
<script src="myobj.js"></script>
<script>
var uno = Singleton.getInstance();
var due = Singleton.getInstance();
(uno===due) ? console.log("equals") : console.log("not equals");
</script>
All works good, only one object is created.
My question is: can I share this object "Singleton" between more HTML pages?
without recreate it in different pages?
If I have (for example) 100 tabs opened on the browser, I would like to use the same object without having the same 100 objects.
Thank you!
Upvotes: 2
Views: 7148
Reputation: 5420
I'm afraid it's not possible across all browsers at the time of writing without the user installing anything. Two partial solutions:
1) Use a browser extension to store the state
Browser extensions can communicate with your pages via the host browser's API and maintain shared state. However, the user must install them.
2) Use LocalStorage
This is shared between pages on the same domain, but only stores strings. You can use JSON.stringify to convert an object to a string and place it on localStorage. http://diveintohtml5.info/storage.html
Upvotes: 2
Reputation: 975
There may not be a way to do it now, but don't completely give up hope; there may be a way to do this soon. There are several good reasons for wanting to share JS objects between pages, but one of them that I've thought about is sharing large persistent data structures between many WebWorkers.
Here are two papers from Berkeley on this very topic, from 2010, so you can see that you're not the only one who wants it...
Berkeley/Google: Object Views: Fine-Grained Sharing in Browsers
Berkeley/Microsoft: Secure Cooperative Sharing of JavaScript, Browser, and Physical Resources
Upvotes: 2
Reputation: 1101
No, it's not possible. You can't keep object between page reloads and you can't share objects between different browser tabs. With cookies you can store some simple data this way, but that's all.
Upvotes: -1