1

I have an already encoded URL string printed in my HTML template via Django. When I place this in a call to location.replace() it gets mangled by some JavaScript that mangles the = and % already present in the query string, resulting in the subsequent URL (out of my domain) not knowing what to do with it.

How do I prevent JavaScript from changing it?

EDIT: example url string:

'http://destination.com/?name=https%3A%2F%2Fexample.com%2F&nextparam=nextvalue'

passing above into location.replace() results a redirect to:

http://destination.com/?name%3Dhttps%253A%252F%252Fexample.com%252Fnextparam=nextvalue

which is obviously incorrect.

The URL has as one of it's query string parameters a URL. The safe encoded characters passed from Django are from the set of characters in the string ':/', basically so the 'http://example.com/' gets encoded correctly. Fine. '=%&' are all untouched parts of the query string.

In my encoded string that works outside of js (eg in anchor tag href) this links to the correct url.

But when I put it in window.location when it redirects it escapes all characters in the query string and removes '&' for some reason - even the '%' used to encode the original URL parameter in the qs. Checking source shows the string is identical to the one in the a tag above.

Is there anyway to prevent javascript location attribute escaping stuff prior to the redirect?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user1561108
  • 2,666
  • 9
  • 44
  • 69

2 Answers2

1

You should decode the query string before calling location.replace() with it.

JavaScript doesn't have a built in method for encoding/decoding strings, but there is a library called php.js that can help you. See this link for a function for decoding urls. This library is widely supported.

Samuel
  • 16,923
  • 6
  • 62
  • 75
  • is there a built-in method for decoding query strings? – user1561108 Sep 26 '12 at 13:09
  • I've expanded on my problem. I only encode some characters prior; others should be left untouched. Sending the url to window.location or location.replace() etc encodes all of the characters prior to redirect for some reason. – user1561108 Sep 26 '12 at 14:14
  • "There is a library for that " is not the same as "That is built in" – Sean Munson Jan 02 '20 at 19:52
1

Consider decoding the query string before calling location.replace() with it.

You can do this using the built-in decodeURIComponent function.

user2428118
  • 7,935
  • 4
  • 45
  • 72