views:

111

answers:

1

I load a JavaScript file which takes current page's URL as a parameter. Here is the code I use:

document.write(unescape('%3Cscript src=\"' + _vis_opt_protocol + 'domain.com/js.php&a='+account_id+'&url='+encodeURIComponent(document.URL)+'&random='+Math.random()+'\" type=\"text/javascript\"%3E%3C/script%3E'));

I thought encodeURIComponent will do the job of properly encoding the URL. However, while loading JS file, browsers interpret the encoded URL too. For example if the document.URL is http://example.com/?test=1#nono then the browser interprets test as another parameter to JS and doesn't send anything after (and including) #nono because it thinks it is an anchor.

What is the best way to encode the URL so that it is passed as it is to the server? I was also toying with base64 or some other form of encoding.

+2  A: 

The problem is that the unescape function you are calling undoes do job of encodeURIComponent. You may try this:

document.write('<script type="text/javascript" src="' + _vis_opt_protocol + 'domain.com/js.php&a=' + account_id + '&url=' + encodeURIComponent(document.URL) + '&random=' + Math.random() + '"><\/sc' + 'ript>');
Darin Dimitrov
Thanks for pointing that out. It was a silly mistake on my part and I keep searching for a solution!
Paras Chopra
The solution is, don't use `unescape`. (Ever! It's a rubbish function.) I think it was being used in `document.write` here to disguise the `</` sequence in the string `</script>`, which would break by ending the enclosing script block early. However, Darin's suggestion of using `<\/` to do that instead is much better.
bobince