Why isnt window.location.href= not forwarding to page using Safari? - javascript

My site lets users login via the Fb button, I'm using the FB / Parse.com JDK for this https://parse.com/docs/js/guide#users-facebook-users
Once the user has been identified, the below code logs the user in and forwards them onto a url. This works as expected under Chrome, but will not work using Safari, the page just stays on the fb.html page which is blank
I've seen that there were some historic issues with
window.location.href=
But, can't find a fix that works for my solution. Does anyone know a way around this?
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
} else {
window.location.href="user_home.html";
}
},
error: function(user, error) {
}
});

Best way work in all browsers:
setTimeout(function(){document.location.href = "user_home.html";},250);

I had this happening to me as well on safari and found this post but found another solution I wanted to add with lots of browser support. Instead of replacing the current location use the method that is on the location object called assign()
document.location.assign(document.location.origin + "/user_home.html")
This also works
location.assign(location.origin + "/user_home.html")
Tested in Chrome and safari on desktop and mobile iOS devices
reference:
https://www.w3schools.com/jsref/met_loc_assign.asp

I think you need to use...
window.location = 'user_home.html';

When I stack to this problem, I made function what working well on any Safari and also all browsers including mobile browsers:
function windowLocation(url){
var X = setTimeout(function(){
window.location.replace(url);
return true;
},300);
if( window.location = url ){
clearTimeout(X);
return true;
} else {
if( window.location.href = url ){
clearTimeout(X);
return true;
}else{
clearTimeout(X);
window.location.replace(url);
return true;
}
}
return false;
};
Is a bit "dirty" solution but give you ability to redirect your page in any case.

Probably because you are doing something before it. In other words, the first step in your click event handler must be window.location.href = "https://example.com";.

I wanted to detect home page but faced same problems for iphone and safari.
I simply added a class called "home" in landing page then just check this class as
if (document.querySelector('.home') !== null) {
// the conditions comes here
}
Details in http://toihid.com/how-to-detect-home-page-in-iphone-and-safari/

Related

Shopify page keep refreshing after being redirected by javascript code

I am trying to create a website https://fone-kase-plus.myshopify.com/ that will detect what device model it's being accessed from (for example GALAXY A40) so it will immediately redirect the user to a corresponding page.
It seems to be working, but it will reload the page multiple times after redirecting. If I try to redirect it to non-shopify page (eg stackoverflow.com) this problem doesn't occur.
function deviceAPIcallback(result){
if(result.deviceName == "desktop"){
window.location.href = "https://fone-kase-plus.myshopify.com/pages/galaxy-a40";
}
else{
alert(result.deviceName);
}
}
Can you please tell me what the problem can be or at least how I can detect it by dev tools?
Thanks
When I go to the site from both my macOS laptop and my iPhone I only get the alert aspect of your function. What does result.deviceName return? You might need to add a third '=' to your first 'if' statement.
function deviceAPIcallback(result) {
if(result.deviceName === "desktop") {
window.location.href = 'https...';
} else {
alert(result.deviceName);
}
}

How to restrict user to navigate back to previous pages and refresh?

Currently I am trying to build a website using ASP.NET MVC5.
I am stuck.
Issue: I want that when user goes to a particular page he/she should not be able to refresh the page, go back to the previous page, copy anything, print screen.
Have tried different solutions like the followings:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
}
<script type="text/javascript">
window.onbeforeunload = function() {
return "Dude, are you sure you want to leave? Think of the kittens!";
}
</script>
<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableF5);
});
</script>
but nothing seem to work.
Please suggest.
You can do this with javascript using the parameters of window.open, for example
window.open('yourUrl','windowName','toolbar=no');
However I would not recommend this. Instead (based on your comment to lujcon's answer) your should design your controllers and view models correctly to prevent the issues you have described. For example, if the user has already answered a question, add a flag, then if they trey to post another answer for the same question, you can check the flag and prevent an update/display error message etc.
The only way I can think of to do what you ask with a web application is to make all of your "pages" a single view that loads the results from multiple Action methods using AJAX. If you load everything using JavaScript/AJAX, the browser won't be able to keep track of any page history.
Don't do that! Web based applications means freedom. User should do anything she/he wants. The question should be: how should I design my application to handle back and refresh button correctly (not disabling them). Disabling printing is useless as at any time user can make print-screen...

Firefox pageMod addon window.location isn't working

I'm building a Firefox Add-on that causes page redirects to happen after keyboard buttons are pressed. The keyboard detection is working just fine, but it just doesn't redirect. The full code is hosted on GitHub (it says the Chrome version but it all Javascript for now). The redirect code in question is also included below. All the code I've ported to Firefox is working just fine in Chrome, so all the Javascript is valid.
// Function that does the redirecting
function goToMsgs() {
if (newNotes){
window.location = "/msg/pms";
}
else if (newSubs) {
window.location = "/msg/submissions";
}
else if (newComms) {
window.location = "/msg/others";
}
else if (newTix) {
window.location = "/msg/troubletickets";
}
else {
$('#keyaffinity-nomsgs').fadeIn(100).delay(500).fadeOut(100);
}
}
// And the keyboard shortcut that triggers it, this still triggers,according to the logs
$(document.documentElement).keyup(function (event) {
// Code omitted
else if (event.keyCode == 77 && control) {
goToMsgs();
}
// Code omitted
});
We need to add full URL for it so Add this things to your code and then check it.
var StrArr = 'http://'+window.location.protocol + '//' + window.location.host;
// Use full URL here
window.location.href = StrArr + '/msg/pms';
MDN seems to recommend assigning simply to window.location, rather than window.location.href.

Firefox 4 onBeforeUnload custom message

In Firefox 3, I was able to write a custom confirmation popup with:
window.onbeforeunload = function() {
if (someCondition) {
return 'Your stream will be turned off';
}
}
Now in Firefox 4, it does not show my custom message. The default message that it provides is not even accurate to what my application does.
Can this default message be overridden?
From MDN:
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
This "Bug" is actually a (imho questionable) feature.. so there's no way to display the message in Firefox 4. If you think it should be changed, comment on that bug so the Firefox developers will know that people actually want to be able to show a custom string.
Addition to the above Answer, I have improved the workaround.
I have used jquery here. you can use default javascript funciton as well.
$(window).bind('beforeunload', function() {
if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
if(confirm("Are you Sure do you want to leave?")) {
history.go();
} else {
window.setTimeout(function() {
window.stop();
}, 1);
}
} else {
return "Are you Sure do you want to leave?";
}
});
Tested and working in firefox 11 as well. :)
My workaround is to show alert in onbeforeunload:
window.onbeforeunload=function() {
if ( /Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
alert("Blah blah. You have to confirm you are leaving this page in the next dialogue.");
}
return "Blah blah.";
}
(It shows two dialogues in Firefox, one dialogue elsewhere.)
Try implementing it with a confirm message,
window.onbeforeunload=function(){
return confirm("Are you sure??");
}
of course when the user confirms then the FF4 message is shown,
so you maybe better display this once per site on login/visit.
A cookie should do the trick.

Catching A Browser Close Event

Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})

Categories

Resources