I have a link to login with facebook on my page and I want to manipulate the way the onclick works. Currently I have changed it so that it does not do the default action by adding return false to the end:
$('#login').on('click', function(e) {
FB.login(function(response) {
//window.easyUserData.login = response;
if (response.authResponse) {
console.log('authorised');
return true;
} else {
// cancelled
}
});
return false;
});
What was happening was that right after it called FB.login to open the dialog it would redirect the page, not what I wanted. What i am looking for is for it to do the default action of the link where i put return true. The return true bit doesn't work because by the time it gets there, return false has already been processed. Any tips on how to do this?
The link has href="#/home" and I am using backbone.js to handle routing.
Due to asynchronous nature of your login function you would have to use a javscript redirect:
$('#login').on('click', function(e) {
var href=this.href;
FB.login(function(response) {
//window.easyUserData.login = response;
if (response.authResponse) {
console.log('authorised');
/* redirect here*/
window.location=href;
} else {
// cancelled
}
});
return false;
});
Related
I'm using React js. I need to detect page refresh. When user hits refresh icon or press F5, I need to find out the event.
I tried with stackoverflow post by using javascript functions
I used javascript function beforeunload still no luck.
onUnload(event) {
alert('page Refreshed')
}
componentDidMount() {
window.addEventListener("beforeunload", this.onUnload)
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.onUnload)
}
here I have full code on stackblitz
If you're using React Hook, UseEffect you can put the below changes in your component. It worked for me
useEffect(() => {
window.addEventListener("beforeunload", alertUser);
return () => {
window.removeEventListener("beforeunload", alertUser);
};
}, []);
const alertUser = (e) => {
e.preventDefault();
e.returnValue = "";
};
Place this in the constructor:
if (window.performance) {
if (performance.navigation.type == 1) {
alert( "This page is reloaded" );
} else {
alert( "This page is not reloaded");
}
}
It will work, please see this example on stackblitz.
It is actually quite straightforward, this will add the default alert whenever you reload your page.
In this answer you will find:
Default usage
Alert with validation
1. Default Usage
Functional Component
useEffect(() => {
window.onbeforeunload = function() {
return true;
};
return () => {
window.onbeforeunload = null;
};
}, []);
Class Component
componentDidMount(){
window.onbeforeunload = function() {
return true;
};
}
componentDidUnmount(){
window.onbeforeunload = null;
}
2. Alert with validation
You can put validation to only add alert whenever the condition is true.
Functional Component
useEffect(() => {
if (condition) {
window.onbeforeunload = function() {
return true;
};
}
return () => {
window.onbeforeunload = null;
};
}, [condition]);
Class Component
componentDidMount(){
if (condition) {
window.onbeforeunload = function() {
return true;
};
}
}
componentDidUnmount(){
window.onbeforeunload = null;
}
Your code seems to be working just fine, your alert won't work because you aren't stopping the refresh. If you console.log('hello') the output is shown.
UPDATE ---
This should stop the user refreshing but it depends on what you want to happen.
componentDidMount() {
window.onbeforeunload = function() {
this.onUnload();
return "";
}.bind(this);
}
Unfortunately currently accepted answer cannot be more considered as acceptable since performance.navigation.type is deprecated
The newest API for that is experimental ATM.
As a workaround I can only suggest to save some value in redux (or whatever you use) store to indicate state after reload and on first route change update it to indicate that route was changed not because of refresh.
If you are using either REDUX or CONTEXT API then its quite easy. You can check the REDUX or CONTEXT state variables. When the user refreshes the page it reset the CONTEXT or REDUX state and you have to set them manually again. So if they are not set or equal to the initial value which you have given then you can assume that the page is refreshed.
I'm trying to perform async operation right before browser redirects user to http://example.com on click.
So, after the ajax call I'm clicking currentTarget again to redirect but it doesn't work.
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
$(".notic_click").on("click", function(e, options) {
options = options || {};
// if it hasn't been clicked already
// run this
if( !options.hasClicked ) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).trigger("click", {hasClicked: true});
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
I tried $(self).off() right before the trigger, but to no avail.
I have already tried this:
window.location.assign(e.target.href);
and this works. But I'm curious as to what is causing the above not to work.
Browser: Mozilla Firefox (78.0.2)
try this out:
$(".notic_click").on("click", function(e) {
if( e.isTrusted) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).click();
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
You can read more about is trusted here: https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
Try it with this code piece. You seem to have a logic problem in your code. Since you prevent the default, you should "return" to the default behaviour:
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
<script>
$(".notic_click").on("click", async function (e, options) {
options = options || {};
e.preventDefault();
console.log('do task here');
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('timeout end');
await new Promise(resolve => setTimeout(resolve, 3000));
window.location = this.href;
});
</script>
Your code appears to work fine in isolation. That being said, a better approach would be to always call preventDefault() to stop the page redirection and then make your async AJAX request. When that request completes you can then use window.location.assign() to redirect the user.
$(".notic_click").on("click", e => {
e.preventDefault();
// I'd suggest putting a loading spinner in the UI here to make it clear
// to the user that their request is in process.
$.get("http://example.com/hello").always(() => {
window.location.assign(e.target.href);
});
});
I am attempting to do a series of actions that has a user logout then redirect them to a home page, using parse in Javascript. Here is the logic:
jQuery(document).ready(function() {
$("#logout").on("click", function (e) {
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut();
// check if really logged out
if (Parse.User.current()) {
console.log("Failed to log out!");
} else {
// redirect page
window.location.replace("home-screen.html");
}
}
});
});
However most times when I logout, back in my parse server, the user session hasn't been destroyed. But I noticed when I remove the window.location action, the user session is destroyed every single time successfully.
So how do I edit my function to say "on click, log user out and ONLY if done successfully THEN redirect page?
Parse.User.logout() returns a promise. Redirect the user after the promise is resolved successfully.
jQuery(document).ready(function() {
$("#logout").on("click", function (e) {
//logout current user
if ( Parse.User.current() ) {
Parse.User.logOut()
.then(function () {
window.location.replace("home-screen.html");
});
}
});
});
I have an iframe that loads what a user requests. However, I need to make sure that the iframe does not load itself and is instead redirected to a default site.
The process has to be dynamic and work on any page, as I have multiple pages doing this, and custom code for each site wouldn't be practical.
As long as you are on the same domain as your parent, you can use parent. Add to the documents having iframes:
$(function() {
// Check if you are in an iframe, otherwise parent == self,
// and the next check will always return true.
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
// Check if parent.url == self.url.
function sameAsParent() {
try {
return parent.window.document.location.toString() === window.document.location.toString());
} catch (e) {
return false;
}
}
if (inIframe() && sameAsParent()) {
// You are being loaded by yourself! Redirect!
window.location.href = 'http://some-redirect-url.com'
}
});
I am struggling with this issue for a couple of hours, but no sign of success. I am trying to implement the facebook login. this is my code:
function fblogin() {
FB.login(function(response) {
if (response.authResponse) {
var url = '/me?fields=name,email';
FB.api(url, function(response) {
$('#email_login').val(response.email);
$('#pwd_login').val(response.name);
$('#sess_id').val(response.id);
if($('#evil_username').val()==""){
$('#loginform').submit();
}else{
// doh you are bot
}
});
} else {
// cancelled
}
}, {scope:'email'});
}
but once i click facebook login button, i am getting too much recursion in console. why is that? i read lots of problems here in stackoverflow regarding this issue, but couldnot find the clue for my case.
i dont have recursion here, but what is happening which causes that recursion?
and there is a call for it from
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx',
channelUrl : '//www.mydomain.de/channel.html',
status : true,
cookie : true,
xfbml : true
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
} else if (response.status === 'not_authorized') {
// not_authorized
fblogin();
} else {
// not_logged_in
fblogin();
}
});
};
and also from normal LOGIN button which triggers the fblogin().
i don't see where your onclick code is or the action that calls fblogin() and i'm assuming the problem is when fblogin() gets called.
function fblogin(event) {
event.stopPropagation();
add an event parameter to each function fblogin(event) call so this can be cross browser compatible.
when an event occurs, it traverses to parent elements so they can inherit the event handler, in your case function fblogin(). when you stop propagation stopPropagation() you stop DOM traversing and the element that calls the function won't pass the handler to the parent if stopPropagation is set. that all means the browser will stop looping through all your DOM elements and making your jquery less recursive.