How do I check if a call to window.location failed because the given URL was invalid, etc? Is there some event I can set on the window object or on some other object that can catch this?
Finally got it to work using a "workaround" that is not a generic solution as I originally hoped:
I am using the fact that the link I am trying to open is a custom url scheme (e.g. myxx://localhost) on mobile, and if it fails, the action I want to perform is a redirection to a standard appstore URL (os-specific). The workaround tries to open the custom URL, and if it fails, the timeout function kicks in shortly after, and opens an alternative url:
setTimeout(function() { window.location=alternateUrl; }, 25);
window.location = customUrl;
The downside is that when the customURL fails, a standard safari browser shows a message box that the site could not be opened, but at least it still redirects the user to the appstore.
Not really possible, because when window.location = someURL is executed, before the URL is even tested, your document is removed from the window. You have no code remaining that could test if it worked.
If the link is on the same origin, you may issue an XMLHttpRequest to test if the page is reachable but there doesn't seem to be a way to test if a page isn't requestable just due to cross origin request or because the URL is wrong.
For a general document, I don't know any way to test if a foreign origin page is reachable (but it can be done for an image using the onload event handler).
you can check if page exists using ajax. didn't test code, but it should work.
var rekuest= new XMLHttpRequest();
rekuest.open('GET', 'http://www.thisdoesnotexits.org', true);
rekuest.send();
if (rekuest.status === "404") {alert("not exist!"); }
Related
I'm not able to get my script to run window.location.replace multiple times. I have a flask application that create files given the unique ids found from streaming access logs on the server. Once the file is on the server, I have a flask route that if the user is redirected to https://somewebsite.com/getFile/<id>, it will than push the file that was created on the server to the client.
Here's my script below:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
var response = '';
if(xhr.readyState === 4 && xhr.status === 200){
response = xhr.responseText;
response = response.substring(0, response.length-1);
response = response.split('\n');
for(x in response){
url_path = response[x];
window.location.replace(url_path);
};
};
};
xhr.open('GET', '{{ url_for('stream') }}', true);
xhr.send();
</script>
I did a few console.log() calls to see if the for loop is running correctly and it is. Even the url_path given to window.location.replace is correct. One thing to note is that when being redirecting to https://somewebsite.com/getFile/<id>, the browser doesn't technically change to that url path, because flask isn't rendering a template, but instead returning a download file, so the browser stays at the current url path after the file is downloaded.
I'm not sure why I am not able to get the script to run window.location.replace more than once. It seems like if there's 2 url_path in the response object, only the last one is being downloaded. Same goes with 3 or 4 paths. Any insight would be helpful. Thanks
An alternative solution I just figured out was instead of redirecting the same browser to multiple urls, why not just open them up in different tabs. I did this by using window.open, which to my surprise did work.
However, my browser pop up blocker did block them out at first, but after changing the settings and allowing pop ups for the page, I was successfully able to have multiple files downloaded to the client. Also, since there's no template rendering on the server side, the tabs themselves don't actually pop up, so the browser won't be flooded with tabs.
I'm still interested in knowing why window.location.replace didn't work if anyone knows why.
Your code is not working because what window.location.replace does is to literally replace the source document (see documentation) with the one provided by the new URL.
What this means is that any code you put after window.location.replace won't be executed.
That is why window.open works perfectly for your situation, because it will open a new document apart from the one it is called. But be careful because not all parameters work for all browsers (check this for compatibility specifications).
I have created a pdf on the server when i use:
function GetPdf(document) {
//Stores the data and creates the html,pdf file
$http.post('createpdf/', document).success(function(data){
console.log(data.filename);
window.open('download2/'+data.filename+".pdf", "_self");
});
I get a error message pop up blocked in google chrome.
When i use the option enable pop ups for this website it all works fine. Is there any way around this ? Because this could be confusing for some users.
But when i use:
window.open('download2/'+data.filename+".pdf", "_self");
It opens the page without warnings but then the main application is replaced by the pdf which is not the result i want to have.
Browsers have strict rules about when they allow JavaScript to show a popup, but they can be summarized as "Only in response to a user action".
Receiving a response to an HTTP request is not a user action, so popups are banned.
The simple solution here is to not use JavaScript. The point of Ajax is to communicate with the server without leaving the page, but you're going to leave the page anyway so there isn't really any point in using Ajax.
Just use a regular form submission.
<form method="post" action="createpdf/" target="_blank">
… then have the server side script redirect to the URL of the created PDF instead of returning the URL as JSON.
I guess you are using and external JavaScript library, I had the same issue on another Project, I used target="_tab" and it worked, I found this on this question.
It's the way Chrome handles popup calls from JavaScript when you use libraries, I used Moment.js to trigger a similar event and got the same issue.
Pop up blocking is not an issue, but a native browser feature that protect the users from popup-hell.
I would recommend to open the PDF in a modal popup instead of a new browser window.
With some jQuery code it is quite easy to implement: documentation is found here
You can always use an alternative route, for example instead of window.open function. You can use the window.location function, perhaps. Windows.location.replace which will relocate you in the same tab.
<script type="text/javascript">
<!--loc can be any changed to your window-->
var loc = "https://google.com/";
window.
window.onclick = function() {
window.open(loc);
}
</script>
Try that :)
window.open is being blocked because you are doing window.open without a click function. Most web browsers will block this feature for security purposes.
how can I check if the document in new window is ready AFTER the document reloads.
Here is my example:
I need to get a search result page to new window from some site (it's cross-domain). I need to first make POST request (they probably store search params in session) and then go to reslut page.
Here is my code:
var windowname = "window"+(new Date().getTime()); // so I can open multiple windows, not very relevant
var new_window = window.open("", windowname); // prepare named window
// prepare form with post data targeted to new window
var dataform = $("<form method='post' target='"+windowname+"' action='https://www.ebi.ac.uk/chembldb/compound/smiles/'><input name='smiles' value='"+$("#id_smiles").text()+"'></form>");
// Need to get the form into page for Mozilla, webkit allows to submit forms that are not in page
$("body").append(dataform);
// submit the form and remove it, no need to keep it
dataform.submit().remove();
// form opens in my new window
$(new_window.document).ready(function(){
// this is carried out apparently too soon, because the POST data didn't work
// when I use timeout (commented below, but i don't like this solution) it works
window.open("https://www.ebi.ac.uk/chembldb/index.php/compound/results/1/chemblid/asc/tab/smiles", windowname);
// setTimeout( function(){window.open("https://www.ebi.ac.uk/chembldb/index.php/compound/results/1/chemblid/asc/tab/smiles", windowname)}, 1000);
});
On that site the first make POST request with AJAX and then they simply, but since it's cross-domain, it is impossible for me.
I believe this is not possible. Even some browser throw exceptions if you use reference of new_window (cross domain).
I got following exception. while trying to access reference of new window with url http://www.google.com (Browser Chrome). and reference has no property with it.
Unsafe JavaScript attempt to access frame with URL http://www.google.co.in/ from frame with URL Document ready in new window, cross-domain. Domains, protocols and ports must match.
You can run the javascript code which is in cross domain, for that you should use either JSONP concept ( http://en.wikipedia.org/wiki/JSONP )/ Cross Origin Resource Sharing( http://en.wikipedia.org/wiki/Cross-origin_resource_sharing ).
Just few changes should be done in apache server settings.
What is the difference between JavaScript's
window.location.href = window.location.href
and
window.location.reload()
functions?
If I remember correctly, window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.
As noted by #W3Max in the comments below, window.location.href=window.location.href will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload() in this case.
Also, as noted by #Mic below, window.location.reload() takes an additional argument skipCache so that with using window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite, and load the page from cache if possible.
If you say window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite.
Note: default value for window.location.reload() is false
The difference is that
window.location = document.URL;
will not reload the page if there is a hash (#) in the URL (with or without something after it), whereas
window.location.reload();
will reload the page.
If you add the boolean true to the reload
window.location.reload(true) it will load from server.
It is not clear how supported this boolean is, W3Org mentions that NS used to support it
There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.
For documentation purposes I would use window.location.reload() because that is what you want to do.
As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:
if (!window.location.hash) {
window.location.href = window.location.href;
} else {
window.location.reload();
}
Came across this question researching some aberrant behavior in IE, specifically IE9, didn't check older versions. It seems
window.location.reload();
results in a refresh that blanks out the entire screen for a second, where as
window.location = document.URL;
refreshes the page much more quickly, almost imperceptibly.
Doing a bit more research, and some experimentation with fiddler, it seems that window.location.reload() will bypass the cache and reload from the server regardless if you pass the boolean with it or not, this includes getting all of your assets (images, scripts, style sheets, etc) again. So if you just want the page to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic.
A difference in behavior between browsers is that when IE9 uses the reload method it clears the visible page and seemingly rebuilds it from scratch, where FF and chrome wait till they get the new assets and rebuild them if they are different.
A difference in Firefox (12.0) is that on a page rendered from a POST, reload() will pop up a warning and do a re-post, while a URL assignment will do a GET.
Google Chrome does a GET for both.
Using JSF, I'm now having the issue with refresh after session is expired: PrimeFaces ViewExpiredException after page reload and with some investigation I have found one difference in FireFox:
Calling window.location.reload() works like clicking refresh icon on FF, it adds the line
Cache-Control max-age=0
while setting window.location.href works like pressing ENTER in URL line, it does not send that line.
Though both are sent as GET, the first (reload) is restoring the previous data and the application is in inconsistent state.
No, there shouldn't be. However, it's possible there is differences in some browsers, so either (or neither) may not work in some case.
from my experience of about 3 years, i could not find any difference...
edit : yes, as one of them here has said, only passing a boolean parameter to window.location.reload() is the difference.
if you pass true, then the browser loads a fresh page,
but if false, then the cache version is loaded...
In our case we just want to reload the page in webview and for some reasons we couldn't find out why!
We try almost every solution that has been on the web, but stuck with no reloading using location.reload() or alternative solutions like window.location.reload(),
location.reload(true), ...!
Here is our simple solution :
Just use a < a > tag with the empty "href" attribution value like this :
< a href="" ...>Click Me</a>
(in some cases you have to use "return true" on click of the target to trigger reload)
For more information check out this question :
Is an empty href valid?
window.location.href, this as saved my life in webview from Android 5.1. The page don't reload with location.reload() in this version from Android.
How can I reload the page using JavaScript?
I need a method that works in all browsers.
JavaScript 1.2 and newer
window.location.reload();
// If we needed to force the document to be fetched from the
// web server again (such as where the document contents
// change dynamically but cache control headers are not
// configured properly), Firefox supports a non-standard
// parameter that can be set to true to bypass the cache:
//window.location.reload(true);
JavaScript 1.1
window.location.replace(window.location.pathname + window.location.search + window.location.hash);
// does not create a history entry
JavaScript 1.0
window.location.href = window.location.pathname + window.location.search + window.location.hash;
// creates a history entry
location.reload();
See this MDN page for more information.
If you are refreshing after an onclick then you'll need to return false directly after
location.reload();
return false;
I was looking for some information regarding reloads on pages retrieved with POST requests, such as after submitting a method="post" form.
To reload the page keeping the POST data, use:
window.location.reload();
To reload the page discarding the POST data (perform a GET request), use:
window.location.href = window.location.href;
Hopefully this can help others looking for the same information.
You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation
JavaScript window.location object can be used
to get current page address (URL)
to redirect the browser to another page
to reload the same page
window: in JavaScript represents an open window in a browser.
location: in JavaScript holds information about current URL.
The location object is like a fragment of the window object and is called up through the window.location property.
location object has three methods:
assign(): used to load a new document
reload(): used to reload current document
replace(): used to replace current document with a new one
So here we need to use reload(), because it can help us in reloading the same document.
So use it like window.location.reload();.
Online demo on jsfiddle
To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.
Try:
window.location.reload(true);
The parameter set to 'true' reloads a fresh copy from the server. Leaving it out will serve the page from cache.
More information can be found at MSDN and in the Mozilla documentation.
This works for me:
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
http://jsfiddle.net/umerqureshi/znruyzop/
To reload a page using JavaScript, use:
window.location.reload();
If you put
window.location.reload(true);
at the beginning of your page with no other condition qualifying why that code runs, the page will load and then continue to reload itself until you close your browser.
location.href = location.href;
Shortest (more)
history.go()
This should work:
window.location.href = window.location.href.split( '#' )[0];
or
var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];
I prefer this for the following reasons:
Removes the part after the #, ensuring the page reloads on browsers that won't reload content that has it.
It doesn't ask you if want to repost last content if you recently submit a form.
It should work even on most recent browsers. Tested on Lasted Firefox and Chrome.
Alternatively, you may use the most recent official method for this task
window.location.reload()
The Javascript reload() method is used to reload the current document or URL. The javascript location.reload(true) method work just like reload button in your browser. By default, the JS reload() method reloads the page from the cache, however you may force it to reload the page from the server side by setting the forceGet parameter to true: location. reload(true).
Source: https://www.coderepublics.com/JavaScript/javascript-location-reload-true.php
What about Depricated?
It is only the reload with forcedReload which is now deprecated. But to avoid depricated error you can use location.reload() without the forceReload flag.