0

I'm trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.

On this page, a JavaScript object is loaded from the page's URL:

http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]

and on this page, I'm trying to create a link to the same page that is shown above, but the URL contains characters that are not allowed in hyperlinks:

http://jsfiddle.net/M6dRb/

<a href = "http://jsfiddle.net/tsUpC/1/show/#["Hello","World!"]">This link doesn't work because the URL contains characters that are not allowed in HTML links.</a>

Is it possible to embed JavaScript objects into URLs without using characters that are not compatible with hyperlinks?

4
  • I'm trying to create a link to this page, but it contains characters that don't seem to work with hyperlinks. jsfiddle.net/tsUpC/1/show/… Commented Mar 14, 2013 at 1:46
  • Wow, the link actually worked when I copied and pasted it into the comment above. I wonder how it was converted into a working hyperlink. Commented Mar 14, 2013 at 1:47
  • It worked because Stack Overflow properly escaped the quotes as &quot; in the HTML. Commented Mar 14, 2013 at 1:58
  • I found a duplicate of this question: stackoverflow.com/questions/3316452/… Commented Mar 14, 2013 at 3:05

2 Answers 2

7

You can put a JSON string in an URL by URL-encoding it before putting it in the URL:

encodeURIComponent(JSON.stringify(object))

In your example, that would be:

http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D

As you might guess, the opposite of encodeURIComponent is decodeURIComponent.

Sign up to request clarification or add additional context in comments.

Comments

-1

You need to encode and decode with JSON

var link = document.getElementsByTagName('a')[0];
link.addEventListener('click', function(){
    // this could also be done with location.hash = JSON.stringify(...);
    var param = JSON.stringify(['your', 'array']),
        href = '#'+this.getAttribute('href');
    href += param;
    location.href = href;
}, false);


// make string an object/array again
var obj = JSON.parse(window.location.hash.substr(1));

4 Comments

I've already figured out that part. Now, I'll need to find a way to generate a link to a URL with special characters, like this one: jsfiddle.net/tsUpC/1/show/…
You will probably need to use javascript to generate or alter the link by adding an onlclick.
It would be better if I could find a way to automatically encode and decode JSON strings to "URL-friendly" strings. There must be some way to do this.
You can do it with most, if not all, server-side languages

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.