Skip to content
Advertisement

Different behavior when setting location from onclick vs href (same js in both)

Why does setting the location in an onlick produce different results than setting it in the href?

    <a href="#" onclick="javascript: location='/mySite/Test/TestLocationPage2.aspx?t=1&tpram=20209&amp;Ref%3dhttps%3a%2f%2flocalhost%2fmySite%2fTest%2fTestLocationPage1.html%3ft%3d1%26tpram%3d20209'">tPram will be: 20209</a>

    <a href="javascript: location='/mySite/Test/TestLocationPage2.aspx?t=1&tpram=20209&amp;Ref%3dhttps%3a%2f%2flocalhost%2fmySite%2fTest%2fTestLocationPage1.html%3ft%3d1%26tpram%3d20209'">tPram will be: 20209,20209</a>

Chrome dev tools show the first query string parameters as:

t: 1
tpram: 20209
Ref=https://localhost/mySite/Test/TestLocationPage1.html?t=1&tpram=20209: 

while the second shows:

t: 1
tpram: 20209
Ref: https://localhost/mySite/Test/TestLocationPage1.html?t=1
tpram: 20209

I’ve tested this in 3 browsers (chrome, firefox, and IE11), and the behavior is the same in all of them, but I don’t understand why.

For any “don’t do that” comments or answers, I’m not looking for advice on best practices.

Advertisement

Answer

    <a href="#" onclick="javascript: location='/mySite/Test/TestLocationPage2.aspx?t=1&tpram=20209&amp;Ref%3dhttps%3a%2f%2flocalhost%2fmySite%2fTest%2fTestLocationPage1.html%3ft%3d1%26tpram%3d20209'">tPram will be: 20209</a>

is equivalent to the below snippet as javascript: is a break/continue label and doesn’t do anything for your onclick event.

<a href="#" onclick="location='/mySite/Test/TestLocationPage2.aspx?t=1&tpram=20209&amp;Ref%3dhttps%3a%2f%2flocalhost%2fmySite%2fTest%2fTestLocationPage1.html%3ft%3d1%26tpram%3d20209'">tPram will be: 20209</a>

The second snippet gets urldecoded when the javascript is loaded into the URL, and then it gets run, the first example gets decoded AFTER it gets run.

    <a href="javascript: location='/mySite/Test/TestLocationPage2.aspx?t=1&tpram=20209&amp;Ref%3dhttps%3a%2f%2flocalhost%2fmySite%2fTest%2fTestLocationPage1.html%3ft%3d1%26tpram%3d20209'">tPram will be: 20209,20209</a>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement