How can I convert this:
http://example.com/?thisurl
to this:
http://example.com/#/thisurl
I have a bunch of old URLs that need to redirect to specific anchors on my page but I can't do it with htaccess because the anchors don't get passed through.
Any thoughts?
Something like this should work:
window.location.href = window.location.href.split('?')[0] + '#/' +
window.location.search.replace(/^?/, '');
You can use the .hash and .search parts of the window.location object like this:
window.location.hash = "/" + window.location.search.substr(1);
This will set the hash without reloading the page.
If you want to reload the page so it has a new URL (without the ?thisUrl in the URL bar, then you could do this:
var wl = window.location;
if (wl.search.length > 1) {
wl.href = wl.href.replace(/\?.*$/, "") + "#" + wl.search.substr(1);
}
Related
I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.
I change current url of the webpage using window.history.replaceState() without refreshing the page. so that I can append to current url YouTube VideoID when ever user clicks on the video which are listed on this page and plays the same video in the same page.
Let us assume sample urls are -
Default Video page
http://www.domain.com/video/
After User clicks on video URL changes to removing the last /
http://www.domain.com/video#Se1y2R5QRKU
I want url to remain with /
http://www.domain.com/video/#wckLzQDTm6s
Here is the script I am using but I am not sure what is remove last / from the url
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = URL.match(regExp);
if (match && match[7].length == 11) {
//console.log(match[7]);
currentURL = document.URL;
// alert(currentURL.slice(0, currentURL.lastIndexOf('#')));
console.log(currentURL.slice(0, currentURL.indexOf('#')));
var sliceURL = currentURL.slice(0, currentURL.indexOf('#'));
var newURL = sliceURL + '#' + match[7];
window.history.replaceState(null, "Video Gallery", newURL);
return match[7];
} else {
//alert("Could not extract video ID.");
}
Because your currentURL initially does not contain the #, the indexOf will return -1 and the result is that the last character (your slash) will be removed. You should explicitly check whether the hash is inside the currentURL before slicing it:
var hashIndex = currentURL.indexOf('#');
var sliceURL = (hashIndex != -1) ? currentURL.slice(0, hashIndex) : currentURL;
I've built a site that uses the History.js plugin to navigate from page to page with AJAX and update the URL accordingly. All works well except in IE; when you refresh the page it essentially loads the content from the first page you came to, not the current pages content. In "decent" browsers it doesn't load the content from any page, it just loads the entire page for that URL, which is what I IE should do.
I'm thinking it doesn't understand what to do with the hash. If you visit http://www.crownacre.voyced.com/contact-us/ it works fine, but when you visit http://www.crownacre.voyced.com/#contact-us/ (with the hash) it doesn't.
I've attempted to redirect the page if it detects a # in the pathname, but there is no way of detecting this as window.location.pathname and History.getHash() returns the path without any hash.
Any suggestions? I've seen a few websites using this plugin that have the same problem, and similar issues on here, but no solution.
Thanks in advance!
I ran into the same problem in my rewrite of tarheelreader.org. I'm using History.js and it is working fine except for the refresh issue in IE8. This hack is working for me.
In my startup code that only runs on initial page load I do:
var url = window.location.href;
if (url.indexOf('#') > -1) {
// ie refresh hack
controller.stateChange();
}
where controller.stateChange() is the state change handler I use for all History changes.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
context = hist.data;
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
You can see all the code in main.js and controller.js at https://github.com/gbishop/TarHeelReaderTheme
Edit
Further exploration has lead to a case where History.js uses the initial URL instead of the root. This hack seems to handle that case.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
bar = window.location.href,
context = hist.data;
//console.log("State changed...", url, context);
if (url != bar && bar.indexOf('#') > -1) {
//console.log('bar = ', bar);
// I think we only get here in IE8
// hack for hash mode urls
var root = History.getRootUrl(),
hashIndex = bar.indexOf('#');
if (root != bar.slice(0, hashIndex)) {
// try to fix the url
url = root + bar.slice(hashIndex);
//console.log('new url =', url);
window.location.href = url;
}
}
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
This worked for me:
<script>
var url = new String(document.location);
if (url.indexOf("#") > -1) {
alert("There is a Hash in the path");
}
</script>
Edit:
function LocationTest()
{
var loc = window.location;
alert(loc.href);
alert(loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
alert(loc.href == loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
}
Sample Source: window.location explained
Maybe a solution:
Can you please try the History.js unofficial version 1.8a2 of my fork from:
https://github.com/andreasbernhard/history.js
...and give feedback? Thank you very much!
I would like to change the url of the page when the user select another page to visit. The url is dynamically replace the original one.
eg.
If user visit page 1 , the url will be book.html?page=1
If page 30 then book.html?page=30 and so on.
However, when I change the link using javascript, it falls into a infinite loop.
It seems I keep visit->change link ->visit ->change link->.... How to fix this problem?
eg. When the link change, don't access the page.
var currURL = $(location).attr('href');
var index = currURL.indexOf('?');
currURL = currURL.substring(0, index != -1 ? index : currURL.length);
// fall into loop
$(location).attr('href', currURL + '?page=' + pageNo);
You can do this pretty easily with just standard javascript.
if(location.href.indexOf('?') !== -1 && location.href.indexof('?page=') === -1)
{
var urlArray = location.href.split('?');
var newURL = urlArray[0] + "?page=" + urlArray[1];
location.href = newURL;
}
Is there is a way how to add hash # to my URL without redirect?
window.location.hash = 'something';
That is just plain JavaScript.
Your comment...
Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.
Try this...
window.location = '#';
Also, don't forget about the window.location.replace() method.
For straight HTML, with no JavaScript required:
Add '#something' to URL
Or, to take your question more literally, to just add '#' to the URL:
Add '#' to URL
window.location.hash = 'whatever';
Try this
var URL = "scratch.mit.edu/projects";
var mainURL = window.location.pathname;
if (mainURL == URL) {
mainURL += ( mainURL.match( /[\?]/g ) ? '&' : '#' ) + '_bypasssharerestrictions_';
console.log(mainURL)
}