Javascript Page Redirect - javascript

I'm trying to use this script that will redirect any webpage to another webpage with a query including the previous webpage's URL.
The code I'm attempting to use looks as such:
window.location = "http://www.readability.com/m?url=" + document.URL;
It's not working though, for what reason I can't figure out. I'm not to familiar with encoding, so this may be the problem. As this works...
window.location = "http://www.readability.com"
But this does not work
window.location = "http://www.readability.com/"
Furthmore I'm working with a mobile browser, not anything like chrome. So it may just be an issue with that, but it may not be. Thanks for reading, and thanks in advance for any help.

You need to escape the URL, otherwise it will be cut on the first & it contains.
window.location = "http://www.readability.com/m?url=" + encodeURIComponent(window.location);
also ignore document.URL and use a more common and interoperable window.location instead.

Don't use escape, since it will not escape all characters you need.You need to escape it with encodeURIComponent:
window.location = "http://www.readability.com/m?url=" + encodeURIComponent(window.location);

Related

how to get page url without decode in javascript?

How can I get page URL from window.location.href without decode in javascript?
For example we can not get exactly this URL: http://example.com/report#title=example_report&url=project_chart%2F%3Fproject_id%3D77.
When we use window.location.href in javascript , we will get this URL:
http://example.com/report#title=example_report&url=project_chart/?project_id=77.
But I want to get exactly the same real URL.
Any solution?
Edited
as #Eugenio told, $(document)[0].URL works fine , but Is it safe?!
Try to use encodeURI.
As for example;
var url = window.location.href;
var originalUrl = encodeURI(url);
This function(encodeURI) encodes special characters,
except: , / ? : # & = + $ #
You can use encodeURIComponent() to encode these characters.
You can use encodeURIComponent, but you have to get the part of a string you want to encode.
encodeURIComponent(window.location.href.split('&url=')[1])
Or you can use RegExp to be more precise.
Just to make a clear and concise answer I will sum up all the comments.
For your problem the best solution is to use document[x].url where x is the index of the URL part that you want to use.
The main difference for your problem between window.location.href and document.url is that the last one gives you the URL in a string format, whilest the other return the URL already parsed.
Using either one is completely normal and safe and is widely adopted in all modern browsers.
var url1 = document.URL;
var url2 = window.location.href;
document.getElementById("documentUrl").append (url1);
document.getElementById("windowLocationUrl").append (url2);
<div id="documentUrl">document.url: </div>
<div id="windowLocationUrl">window.location.href: </div>
There is no difference in this particular snippet example because there are no parameters attached to the URL. Anyway, hope this helped. Cheers!
as #Eugenio told,
i use below code and it works fine:
var url = $(document)[0].URL;

Javascript regex to replace ampersand in all links href on a page

I've been going through and trying to find an answer to this question that fits my need but either I'm too noob to make other use cases work, or their not specific enough for my case.
Basically I want to use javascript/jQuery to replace any and all ampersands (&) on a web page that may occur in a links href with just the word "and". I've tried a couple different versions of this with no luck
var link = $("a").attr('href');
link.replace(/&/g, "and");
Thank you
Your current code replaces the text of the element within the jQuery object, but does not update the element(s) in the DOM.
You can instead achieve what you need by providing a function to attr() which will be executed against all elements in the matched set. Try this:
$("a").attr('href', function(i, value) {
return value.replace(/&/g, "and");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
link
link
Sometimes when replacing &, I've found that even though I replaced &, I still have amp;. There is a fix to this:
var newUrl = "#Model.UrlToRedirect".replace(/&/gi, '%').replace(/%amp;/gi, '&');
With this solution you replace & twice and it will work. In my particular problem in an MVC app, window.location.href = #Model.UrlToRedirect, the url was already partially encoded and had a query string. I tried encoding/decoding, using Uri as the C# class, escape(), everything before coming up with this solution. The problem with using my above logic is other things could blow up the query string later. One solution is to put a hidden field or input on the form like this:
<input type="hidden" value="#Model.UrlToRedirect" id="url-redirect" />
then in your javascript:
window.location.href = document.getElementById("url-redirect").value;
in this way, javascript won't take the c# string and change it.

Why does this dropdown list for sorting work in Internet Explorer but not in Chrome?

I have some JavaScript for a dropdownlist to sort results on a product inventory page. In Internet Explorer the sorting works fine and the browser handles this perfect. However in Chrome it fails every time (can you believe it, something works in IE but not Chrome?)
In IE when I use the Sort By option the URL looks like this:
MyExampleSite.com/Supplies/Products/12345/MyProduct/?a=0
However when I do the Sort By option in Chrome here is what the URL looks like:
MyExampleSite.com/Supplies/Products/12345/MyProduct/?&a=0
As you can see it adds the amp in the URL, and if I keep trying to sort it just add's an additional amp everytime.
Here is the JavaScript which caused my issues:
$("[name=a]").change(function () {
window.location = '#(this.Model.SortUri)' + '#(this.Model.SortUri.IndexOf('?') == -1 ? "?" : "&")a=' + this.value;
});
My Solution was to add Html.Raw like this:
$("[name=a]").change(function () {
window.location = '#(this.Model.SortUri)' + '#Html.Raw(this.Model.SortUri.IndexOf('?') == -1 ? "?" : "&")a=' + this.value;
});
And suddenly it works fine in IE and Chrome.
My question is why did Chrome do this but not IE?
Well, you need to make sure all your stuff is encoded correctly, and I'm guessing you aren't. We would need to see much more of your page to determine that. IE is probably detecting that you've done it incorrectly and attempting to fix it for you, while Chrome isn't auto-fixing your mistake.
It gets pretty complicated as to the rules of when you do and don't need to escape stuff. It's in a HTML page, and everyone knows you need to escape & in HTML pages, but it's in a script tag, so do you or don't you need to escape it? Well that depends if you also have the script tag in a CDATA element or not.
The simple solution is to avoid doing that. Put the URL you want to switch to on the [name=a] element as a data tag like so:
<sometag name='a' data-urlprefix='#(this.Model.SortUri)#(this.Model.SortUri.IndexOf('?') == -1 ? "?" : "&")a='>stuff</sometag>
Then in your javascript:
$("[name=a]").change(function () {
window.location.href = $(this).data('urlprefix')+encodeURIComponent(this.value);
});
This also has the benefit of moving the server processing stuff to just the HTML parts, so that you can put the javascript in it's own file, which you should be doing anyhow.
Note that you should be urlencoding this.value if it isn't already as well, so I've done that. If it is already encoded, you can safely remove it. I've also changed window.location to window.location.href because window.location can do strange things sometimes as well -- encoding on some browsers, but not on others, etc.
You just need to make the entire string as part of your Html.Raw(build ou the logic outside and directly insert that variable here)
Please check this post
Why is Html.Raw escaping ampersand in anchor tag in ASP.NET MVC 4?

Javascript - how to remove domain from location.href

I need to remove the domain name from location.href using Javascript. I have links like: http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO and I need to have links without http://localhost and in future without it's real domain name.
I will use those trimed links in Javascript function so I would like to trim it also in Javascript.
I have tried: window.location.href.split('/')[2]; but I could only get domain form it. And I want to get rid of domain.
Any help here much appreciated!
Use window.location.pathname. This gives you the path relative to the host. See here for more details.
For any arbitrary URL, assuming that the variable url contains your URL, you can do:
url = url.replace(/^.*\/\/[^\/]+/, '')
Rather than doing string manipulation on window.location.href, you can use the other properties of window.location. In your case, you want the pathname, the search and the hash:
console.log(window.location.pathname + window.location.search + window.location.hash);
I posted this on your other question as a comment but I might as well add it here too. You can use a replace with a regex, like this:
location.href.replace(/.*\/\/[^\/]*/, '')
Things have changed a bit since 2011 when the original answer was posted. Now you can use the URL Web API.
https://developer.mozilla.org/en-US/docs/Web/API/URL
For your question, the following code:
let dummy_url = new URL("http://localhost/App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO");
console.log( "pathname : " + dummy_url.pathname );
console.log( "search : " + dummy_url.search );
console.log( "both : " + dummy_url.pathname + dummy_url.search );
Generates the following output.
pathname : /App/User/UserOrder.aspx
search : ?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
both : /App/User/UserOrder.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
The combined pathname and search fields is what you want.
As of Nov 2021 this is available in everything except IE and Opera Mini.
Try this:
window.location.pathname
Fiddle: http://jsfiddle.net/maniator/zKruK/

Replace end characters of current URL with bookmarklet

Is there a way to replace all characters after the last backslash in the currentURL with another string via javascript bookmarklet?
I'm doing a lot of auditing work with Sharepoint sites and having to manually look at the settings pages for sites by entering strings to the end of a URL. For example, I might go to a site like:
https://site.com/..../default.aspx
And I replace the "default.aspx" with "_layouts/user.aspx" and reload the new page so it is now at:
https://site.com/..../_layouts/user.aspx
It's not always "default.aspx", so I can't just use a simple string replace. I know there is a way to manipulate the URL via a javascript bookmarklet, but my knowledge of how to do that is limited at best. Any help or guidance would be greatly appreciated
I don't know if this is what you thought, but if you just want to change the last part of the url with something else, you could use this bookmarklet
javascript:(function(){
var curloc = document.location.href.split('/');
var urlEnding= '/_layouts/user.aspx';
curloc = curloc.splice(0,curloc.length-1).join('/')+urlEnding;
document.location.href = curloc;
})();
You could replace the fixed url with
prompt('Enter your url:', '_layouts/user.aspx');
if you need to change the last part each time.
I hope this helps.

Categories