inconsistent window.history.pushState uri encoding - javascript

Take url address www.somesite.com/#user1
If I click on a good old fashioned <a href... hyperlink containing the link then the # is percent encoded to %40 in the address bar.
If I use html5's window.history.pushstate("object or string", "Title", 'www.somesite.com/#user1') the # is not endocded - it instead shows as a '#' character.
This inconsistency troubles me. Mayhaps there is a way to make the behaviour consistent?
I have considered encodeURIComponent('www.somesite.com/#user1') for the pushstate url, but this also encodes the '/', and what I am hoping is for the <a href... hyperlink not encode the '#' symbol.

Using encodeURIComponent makes javascript assume there are no special HTTP characters to ignore.
extract the compnenet first:
var url = "www.somesite.com/#user1";
var atPos = url.indexOf('#');
var urlComp= url.slice(atPos); //#user1
url = url.slice(0, atPos);
url += encodeURIComponent(urlComp); //"www.somesite.com/%40user1"

Related

JavaScript fetch API call with string interpolation with string contains # always null

If I pass a string as "testabc#" it breaks somewhere on the way route to the controller. I'm not sure why the # is causing me the issue. Is this a key work in JavaScript causing the issue? I have tried all other different specials characters and they work just fine. Has anyone else come across this issue.
`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`,
Anchor (#) is a feature of URL called fragment and it is used for internal page references. Using a question mark (?) and ampersand (&) can break your HTTP request like an anchor does because all of these things are URL features and it changes URL behavior.
To avoid this kind of error you must use encodeURI() or encodeURIComponent() like below:
with encodeURIComponent():
var url = `/api/Controller/UpdatePassword?currentPassword=${encodeURIComponent(currentPassword.value)}&newPassword=${encodeURIComponent(newPassword.value)}&confirmPassword=${encodeURIComponent(confirmPassword.value)}`
with encodeURI():
var url = encodeURI(`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`)
# in a url is a special character which indicates a "fragment", which means a special part of the url which is an anchor in the page, of sorts. Thats why it breaks your code. ? And & are also special, and so are a few others.
You should url encode data that you pass in the url.
Try use encodeURI() to the url string before fetching, like:
var url = `/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`
encodeURI(url)

Remove the # character from url

I have a js-slider and it's url is changed every time, when changes pictures.
I want to remove /#/ from url.
document.location.href = String( document.location.href ).replace( "#/", "");
It's work, but plugin jquery.address.js doesn't view page and redirected to 403.
How can I remove this symbol and the slider would work.
site: http://taron-julhakyan.ru
Thankes!!!
You can use regexp in javascript
document.location.href = document.location.href.replace(**/(#)[0-9A-Za-z-]+/ig, "#/"**);
Here the /ig suffix says that the regex is case insensitive and and global stating.
For more information refer here

Encode url but keep working

Weird one but is it possible to make Link work without the text helloworld.com being in the source?
Long story but I have function breaking helloworld because it matches it and I remember back to my AOL days where you could "encode" a url to look completely different text but it still took you to that url? Note I dont mean encoding the ? or = etc - but the actual text of domain name... have I completely imagined this?
Weird one but is it possible to make Link work without the text helloworld.com being in the source?
To what end? If you want to totally prevent users from figuring out the URL before they click the link, no that's impossible. If instead you just want to prevent that URL from being picked up by scrapers that don't run JavaScript, then yes that is entirely possible.
What I would do in that case is add a data attribute to the link with an encoded version of the URL.
Link
Then in your JavaScript, decode. Untested jQuery example to get you started:
$('a[data-href-rot13]').each(function (index, el) {
$(this).attr('href', rot13($(this).attr('data-href-rot13')));
});
Of course, you might want a different algorithm than rot13. You could use AES and base-64 encode the output for use in the tag. In case you do want rot13, see this post: https://stackoverflow.com/a/15747894/362536
You can url encode your URL:
(here just on the 'l' character)
Hello World !
It's not an encryption, but a simple encoding. Url cannot use all characters inside of them, so special chars can be passed with the form %XX where XX is the hexadecimal representation of the char.
You browser will decode it, before using it. This coding is normally seen after the url for params and path (ie: url.com/this%20space), but it is also available inside the domain name.
You can encode an url like that with this short javascript:
var encodeUrl = function(url) {
return url.split('//')[0] + '//'
+ url.split('//')[1]
.replace(/[a-z ]/gi, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
url = 'http://www.helloworld.com/';
encodedUrl = encodeUrl(url)
document.body.innerHTML = 'Raw url: <pre>' + url + '</pre>EncodedUrl: <pre>' + encodedUrl + '</pre>Result: TEST';

Encoding URL in JavaScript

I'm unable to encoding data URI:
var uri ="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQo...";
var res = encodeURI(uri);
document.location.href = 'display.jsp?img='+res;
After encoding, I'm getting the same uri. display.jsp is landing as am empty page.
There is no encoding happening because what you have there is already a valid, completely encoded URI.
If you want to use that as a parameter in an other URI, you should use encodeURIComponent:
document.location.href = 'display.jsp?img='+encodeURIComponent(uri);
It is not correct to use encodeURI() as this function encodes special character except: , / ? : # & = + $ #
Use encodeURIComponent() to encode these characters.
For more info check below link:
http://www.w3schools.com/jsref/jsref_encodeuri.asp
Your problem is that the encodeURI function is for making a URL valid for a browser, not for formatting content into a URL (which is what you're doing). A base64 string is already formatted in such a way that it registers as valid. To encode it as part of the URL, you need to use encodeURLComponent.
Basically, just use:
var uri ="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQo...";
var res = encodeURIComponent(uri);
document.location.href = 'display.jsp?img='+res;
For more info, check out: When are you supposed to use escape instead of encodeURI / encodeURIComponent?

How can I submit a hash key in an URL parameter?

I have a Spring-MVC application with Freemarker as the view component.
In my templates, several links are generated which point back to my application and which include URL parameters containing a hash key (#).
Example:
parameter: Q#106368 11
URL generated by Freemarker with encoded param: testurl.html?key=Q%23106368%2011
I use JavaScript to redirect to this URL (reason: I use JS to manage loading of 2 frames at the same time).
The redirect method is simple:
function redir(url) {
window.location.href = url;
}
The JS call generated by Freemarker looks like
test
My problem is that the browser / Javascript converts back the URL encoded parameter, thinks there is a # and cuts off there.
When I use window.location.href='http://...' directly it works. Only when using the method parameter it seems to be magically URL decoded and then the redirect fails because the URL gets cut off at the #.
Is there an easy way to transmit the parameter correctly?
I am aware that I could replace the #, e.g. with $$$hash$$$, in the template and do the replacement on the server side again. But there are so many places I would have to change...
As Marc B commented, it is necessary to URL encode again. The method would be encodeURI(). However, this method does not encode the # sign. For my specific use case, I have to replace the # sign with %23 after the encoding.
The redirect JS method finally looks like:
function redir(url) {
url = encodeURI(url);
url = url.replace(/#/g, '%23');
window.location.href = url;
}
Comparing escape(), encodeURI(), and encodeURIComponent()
encodeURIComponent/decodeURIComponent is more thorough than just encodeURI, it will decode/encode '#' and event '/'
What browser are you using? I'm trying FireFox 5 and it doesn't convert %23 back into # in my testing. When you mouse over the link or copy the link location, what does that have? Are you sure whatever is outputting the link isn't doing the conversion?
Update
This isn't ideal, but it seems like it solves the problem:
<a onclick="url = 'http://localhost:8080/testappp/testurl.html?key=Q%23106368%2011';" href="javascript:redir(url);">test</a>
It seems like the href attribute is decoded. When I mouse over it I seen the # instead of the %23.

Categories

Resources