What is the recommended way to pass urls as url parameters?

encodeURIComponent() should work. For example,

'&url=' + encodeURIComponent("http://a.com/?q=query&n=10")

produces

"&url=http%3A%2F%2Fa.com%2F%3Fq%3Dquery%26n%3D10"

(which doesn't have any & or ? in the value). When your server gets this url, it should be able to decode that to get the original:

param["url"] = "http://a.com/?q=query&n=10"

I'm not sure what server you're using (e.g. Rails, Django, ...) but that should work "out of the box" on any normal system.


Using '&url='+encodeURIComponent(url); to pass a URL from browser to server will encode the url

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string.

but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.

Then the server is very broken indeed. If that's really what's happening, you need to fix it at the server end.

Code?


I ran into this issue, personally I couldn't use any of the accepted answers, but it can also be done by just encoding the url into Base 64, passing it as a parameter, and then decoding it. With javascript, you can encode a string s to base 64 with btoa(s) and decode with atob(s). Other languages have ways of doing the same thing. Base 64 is just kinda like representing a larger series of characters with 64 character(For ex, all the capital letters, all the lowercase, and a couple symbols). Kinda like how we represent letters in Binary. But it's nice to use, because then we can just pass base64 strings as parameters, and then they won't interfere/get interpreted in a weird fashion, and then we can decode them at the next stage.