14

I have created a bookmarklet that tries to read and write with localStorage with the following data: url:

data:text/html;base64,PGRvY3R5cGUgaHRtbD4KPGh0bWw+Cjxib2R5Pgo8c2NyaXB0Pgpsb2NhbFN0b3JhZ2Uuc2V0SXRlbSgnY29udGVudCcsICdoZWxsbyB3b3JsZCcpOwpkb2N1bWVudC53cml0ZShsb2NhbFN0b3JhZ2UuZ2V0SXRlbSgnY29udGVudCcpKTsKPC9zY3JpcHQ+CjwvYm9keT4KPC9odG1sPg==

This translates to following code in the browser:

<doctype html>
<html>
<body>
<script>
localStorage.setItem('content', 'hello world');
document.write(localStorage.getItem('content'));
</script>
</body>
</html>

This code tries to write the string hello world to the browser's localStorage, read the string and finally write it to the page.

However, this results in the following error:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Storage is disabled inside 'data:' URLs.

As this approach doesn't work, it brings me to the question: How to save data to the browser with data: URL? Is there some other API than localStorage that I could use to save data in data: URLs?

EDIT:

Cookies do not work. Trying to access cookies gives the following error:

Uncaught DOMException: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.

EDIT 2:

File system API does not work either. Fails with the error object:

file error

10
  • 2
    Sounds like an XY problem. What is higher level use case?
    – charlietfl
    May 22, 2016 at 20:27
  • 2
    You can't because local storage isn't supported in data-urls. Check this.
    – The Alpha
    May 22, 2016 at 20:28
  • @charlietfl Creating a simple "notepad" where I could persist textual content in the browser even when offline or when the browser is restarted.
    – jehna1
    May 22, 2016 at 20:31
  • @TheAlpha updated the question to be more clear
    – jehna1
    May 22, 2016 at 20:33
  • 1
    I don't know why you need a data-uri and it doesn't seem possible using the data-uris. However, you can do access localStorage from a bookmarklet, though the data you get/set will be tied to the URL of the page you're on when you run the bookmarklet. Just use: " javascript:localStorage.setItem('content', 'hello world'); document.write(localStorage.getItem('content'));"
    – Luke H
    May 30, 2016 at 19:19

8 Answers 8

13
+200

@charlietfl Creating a simple "notepad" where I could persist textual content in the browser even when offline or when the browser is restarted.

Working off the notepad use case, the following is a simple solution which works offline, when the browser restarts, persists across multiple devices (if you have your history shared across your different browsers) and you could argue comes with the added bonus of versioning built in...

One 'storage' mechanism you have available is the actual url so using it seems like a possible choice. As long as your happy for the url to change in this situation then you could build on top of the following.

<!doctype html>
<html>
<body>
<div id="editable" contenteditable="true">
    My notepad!
</div>
<script>
    document.getElementById('editable').addEventListener('blur', function (event) {
        window.location = 'data:text/html;base64,' + btoa(document.documentElement.outerHTML);
    });
</script>
</body>
</html>

Hope this help!

6
  • Thank you, this answer works perfectly! It actually stores the content to the browser (the browser's history database) and I'm able to access it even if I close the browser. I can also "save" the content permanently to the browser by bookmarking the modified URL.
    – jehna1
    May 31, 2016 at 20:00
  • Glad I could help @jehna1! Figure you can also slowly enhance the code as well as you continue to use it as well. i.e. adding #editable:focus {outline:none;} could be a start.
    – Ian
    May 31, 2016 at 20:04
  • 1
    Yep, I'm building the code as we speak. I'll be open-sourcing the bookmarklet when I get it polished and ready :)
    – jehna1
    May 31, 2016 at 20:13
  • 1
    If you can let us know via a comment when you do that would be great! I think this is an interesting direction for note taking and I've been looking for a simple solution in place of nvALT etc.
    – Ian
    May 31, 2016 at 20:18
  • Totally forgot to post this here, but now the notepad is published and I've been using it for a while now. Github: github.com/jehna/notepadlet Blog post: thejunkland.com/blog/…
    – jehna1
    Jul 31, 2016 at 13:44
6

You can use Blob() , URL.createObjectURL()

<!DOCTYPE html>
<html>
<head>
  <script>
    window.onload = function() {
      var html = "<!doctype html>\
                   <html>\
                     <body>\
                       <script>\
                         localStorage.setItem('content', 'hello world');\
                        document.write(localStorage.getItem('content'));\
                      <\/script>\
                     </body>\
                   </html>"
      , blob = new Blob([html], {
        type: "text/html"
      })
      , url = window.URL.createObjectURL(blob)
      , a = document.getElementById("bookmark");
      a.href = url;
    }
  </script>
</head>
<body>
  <a id="bookmark" target="_blank">click</a>
  </body>
</html>

plnkr http://plnkr.co/edit/EyzUwJrlgD7GTNWnfjwe?p=preview

1
  • This is a great answer, but it still needs an initial source domain where the blob URL is bound to. If I run it from the data: URL directly, it gives the following error: Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document. and the resulting URL is blob:null/5afcf8cd-10f5-410d-aacb-e5ea4a693495.
    – jehna1
    May 31, 2016 at 19:56
6

Short answer: Its not possible! This is because all storage mechanisms are bound to the origin for security reasons. This is required so that one page can not access the data of another. In a data URL you don't have an origin, so how should the browser bound the data to your page?

Long answer: You probably don't need it for your use case. I refer you comment:

@charlietfl Creating a simple "notepad" where I could persist textual content in the browser even when offline or when the browser is restarted.

This can be archived much easier! Don't use a data URL for this! Probably you store the data url as a bookmark, so either way once the user need to access your website to add this bookmark. Use that occasion to do something else: Give the user a normal webpage with an Application Cache Manifest. With that you will have a normal page with all the usual abilities like access to the localStorage because you are bound to an origin. Thanks to the Application Cache Manifest this page will never reload. It will survive a browser restart and works completely offline. You just need internet on the first visit to install the app.

This is supported by all major browsers, and for your simple use-case easy to implement!

1
  • Thank you for your answer! This solution still needs a web server at the first place to have a domain, but It's a good workaround though.
    – jehna1
    May 31, 2016 at 19:53
2

I used to use this bookmarklet as my browser's homepage:

data:text/html, <body contenteditable onblur="window.location='data:text/html;base64,'+btoa(document.documentElement.outerHTML);"/>

But Chrome does not seem to allow updating location from within data uri pages...

1

As was mentioned in a few comments on your question, local storage isn't supported in data: urls. That's the only answer we can give you, because at least at the moment that is the way most browsers handle that.

The reason for that design decision seems to be because local storage is tied to the origin of the document, so that my website can't access local storage set by google.com, etc. In the case of data: urls there isn't an origin in any meaningful sense of the word. file: urls have local storage enabled in some browsers (I believe Firefox for sure, I don't know about Chrome) because there the origin is at least the local filesystem. A data: url has no origin, so there is no scheme by which to sort its local storage data.

As it stands, Chrome has declared this to be the intended behavior and they are not likely to change it unless the local storage spec is updated to explicitly say otherwise, Firefox seems to be leaning the same way, and I don't know about IE, but they're likely to have followed suit.

9
  • Is there some other API than localStorage that could be used to save data within the data: url?
    – jehna1
    May 22, 2016 at 20:55
  • You could try using JavaScript to set cookies, but I believe those are tied to the origin as well. I'm not sure exactly how it would behave. May 22, 2016 at 21:04
  • As my question is about "how to save data" rather than "why does this code not work", I unfortunately can not accept your answer. If you get the cookie based approach working and update your answer to include a working demo, I'd be happy to accept it
    – jehna1
    May 22, 2016 at 21:14
  • @jehna1 You could accept this post on the basis it explains why what you want is impossible (for security reasons). I doubt you will ever be accepting a working demo.
    – traktor
    May 22, 2016 at 23:24
  • If you give me another day or so I can see if cookies or any other technology will allow browser storage on data: urls. May 23, 2016 at 0:52
1

local storage is not supported in data: urls. if you really want to store the data to client side set cookies this is the only way to do this.

3
  • Can you provide a working code for this? As I've stated at the question, accessing document.cookie throws an error like localStorage.
    – jehna1
    May 26, 2016 at 11:00
  • see this Link hope this will help you May 26, 2016 at 11:20
  • 2
    That link points to a page that describes PHP's setcookie function? That's server side, so it unfortunately does not help.
    – jehna1
    May 27, 2016 at 6:40
1

Why not use 0x0 images to query a HTTPS origin that simply stores data in a query string to a cookie so you can retrieve it by loading a dynamic script file based on the cookie content? If that origin caches itself, it will run offline.

5
  • Welcome to Stack Overflow! I recommend against rhetoric questions in answers. They risk being misunderstood as not an answer at all.
    – Yunnosch
    Feb 10, 2021 at 21:05
  • The technique allows you to create cross-origin storage. I've never tried it myself, but I know it would work. It uses a technique similar to advertiser tracking.
    – 9pfs
    Feb 10, 2021 at 21:06
  • 3
    I think that is not an answer to my comment. Please edit it into the post.
    – Yunnosch
    Feb 10, 2021 at 21:07
  • I think what you're describing is using a server to store user-submitted data to a plaintext cookie? This would require a network connection for saving data, which I don't want (although reading could be done offline too).
    – jehna1
    Feb 12, 2021 at 5:57
  • What about employing a service worker for that, so the data could be accessed as long as the device has internet prior to offline?
    – 9pfs
    Feb 23, 2021 at 19:24
-1

Storing information locally on a user’s computer is a powerful strategy for a developer who is creating something for the Web.

if you working on a web application then you have two types of web storage which helps you can store & retrive the data in Client Browser. these two storage are

1. Local Storage
2. Session Storage

Both of the storage maintain a file which contain data per Unique URL ID in object form of key value pair. for this purpose you can use any storage localStorage() or sessionStorage().

for every user browser creates a unique URL ID so when you trying to retrieve the data from these storage you need this unique URL to retrieve the data. if you don't want to use this unique url you can also implement your own custom combination for generate URL.

These storages is used for different purposes & have their own features.

when you store your data in localStorage then you can access any time when you come back after closing the browser by follow that particular Unique URL.

On the Other hand when you are using sessionStorage for store & retrieve data then you can access data only whenever browser is open. when closing the browser it will clear your all data. and when you come back you will be found nothing is exist on that URL. and

Now, example for store & access the data from localstorage.

var car = {};
car.wheels = 4;
car.doors = 4;
car.sound = 'Boss';
car.name = 'Audi R8';
localStorage.setItem( 'car', JSON.stringify(car) );
console.log( JSON.parse( localStorage.getItem( 'car' ) ) );

when you try to store & access the data by following the url then.

if(localStorage && localStorage.getItem('car')){
    console.log(JSON.parse(localStorage.getItem('car')));
}else{
     $.getJSON("http://query.yahooapis.com/xyz?user1",function(data){
        if(localStorage){
            localStorage.setItem('car',JSON.stringify(data));
        }
        console.log(data);
     });
}

Well i hope it will giving you an idea to deal with web storages. for more information about store & access data from web storage. click here..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.