Reload Parent Window without POST - javascript

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.

Related

Page refresh goes back to home page when using History.js in ie9 and below

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!

Dynamically modify the url using javascript

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;
}

Bitly API - JavaScript function to open new window

I am using a script i found here to dynamically generate short link for my Tweet buttons and it works perfectly well, but the only thing i cant seem to do is create the link to open in either a new tab or preferably a popup window.
I have tried several variations of the window.location section of the script but so far I've had no luck. If anybody could point me in the right direct I'd be very grateful.
This is the script I am using...
<script>
var TweetThisLink = {
shorten: function(e) {
// this stops the click, which will later be handled in the response method
e.preventDefault();
// find the link starting at the second 'http://'
var url = this.href.substr(this.href.indexOf('http:', 5));
BitlyClient.shorten(url, 'TweetThisLink.response');
},
response: function(data) {
var bitly_link = null;
for (var r in data.results) {
bitly_link = data.results[r]['shortUrl'];
break;
}
var tweet_text = "Text for the Tweet goes here"
window.location = "http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
}
}
jQuery('.tweetlink').bind('click', TweetThisLink.shorten);
</script>
Many thanks in advance :)
Normally you could just do window.open:
window.open("http://twitter.com/home?status=" + encodeURIComponent(tweet_text + ' ' + bitly_link + " #Hashtag1 #Hashtag2");
BUT, since you are doing an ajax call before this happens, chances are that this window popup will be blocked by the browser, since the window.open command is no longer associated with the click (browsers allow a certain time before a window.open command falls under non-initiated "popup").
A solution would be to first open the window on click (in your shorten function):
var win = window.open('about:blank');
And then redirect in your response function:
win.location = 'http://twitter.com/etc...';
Demo: http://jsbin.com/usovik/1
Perhaps you're looking for
window.open("http://example.com");

Automatically reload an iframe if source page changes

I don't know what's wrong with my code, even if I change the content of the target file it still wont refresh the iframe.
<script type="text/javascript">
var page = 'data/apps/<? echo $_SESSION['name']; ?><? echo $_SESSION['last']; ?>App.html', lM;
function checkModified(){
$.get(page, function(a,a,x){
var mod = x.getResponseHeader('last-modified');
if(lM != mod){
lM = mod;
document.getElementById("frame").src += "";
}
}
}
setInterval(checkModified, 5000); // every 5 seconds
</script>
What I want to achieve is when there are changes on the target page, the iframe will automatically reload itself so that the changes can be shown to the user. Both pages are located in the same domain.
Firstly, you had a missing closing bracket ")" at the end of the $.get method.
The main problem, though, was probably that your server is not sending proper Last-Modified headers. The server I tested on didn't send any, meaning mod is undefined. A workaround is to check for Content-Length instead. It's not ideal because an edited page doesn't necessarily change size, but it seems you're in control of the page so you could ensure you add an extra byte to force a refresh.
Here is your checkModified function updated which should work:
function checkModified() {
$.get(page, function(a, b, x) {
var mod = (x.getResponseHeader('Last-Modified')) ? x.getResponseHeader('Last-Modified') : x.getResponseHeader('Content-Length');
if (lM != mod) {
lM = mod;
console.log('Fetched');
document.getElementById("frame").src += "";
}
});
}

JavaScript redirect based on domain name

I am not looking for a simple redirect.
What I am trying to do is this.
Person A loads site BOB.com and clicks a link to page X.
Person B loads site TIM.com and clicks a link to the same page X.
Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello.
If user came from TIM.com then redirect to Tim.com/hello.
If user didnt come from ether then redirect to Frank.com/opps.
This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". It should ignore everything past the ".com".
This is the script I started with.
<script type='text/javascript'>
var d = new String(window.location.host);
var p = new String(window.location.pathname);
var u = "http://" + d + p;
if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
{
u = u.replace(location.host,"bob.com/hello");
window.location = u;
}
</script>
Use document.referrer
if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
window.location = "http://bob.com/hello";
}
else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
window.location = "http://tim.com/hello";
}
else {
window.location = "http://frank.com/oops";
}
Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com; the regex is more robust.
document.referrer is the place to be
Use document.referrer to find where the user came from.
The updated code is
<script type='text/javascript'>
var ref = document.referrer,
host = ref.split('/')[2],
regexp = /(www\.)?(bob|tim).com$/,
match = host.match(regexp);
if(ref && !regexp.test(location.host)) {
/* Redirect only if the user landed on this page clicking on a link and
if the user is not visiting from bob.com/tim.com */
if (match) {
ref = ref.replace("http://" + match.shift() +"/hello");
} else {
ref = 'http://frank.com/oops';
}
window.location = ref;
}
</script>
working example (it displays a message rather than redirecting)

Categories