I need to logout an user if he/she tries to submit any valid URL from the address bar?
I tried jQuery on items below but it is not working.
window.location.href
window.unload
unload code
(window).unload(
function(event) {
//code to handle
});
location href code
(function() //create a scope so 'location' is not global
{ var location = window.location.href;
setInterval(function()
{
if(location != window.location.href)
{
location = window.location.href;
window.location.changed(location);
}
}, 1000);
}
)();
window.location.changed = function(e)
{ console.log(e);//outputs http://newhref.com
//this is fired when the window changes location
}
Related
I have the code below which asks for confirmation when a user tries to reload the page. It works fine
window.onbeforeunload = function(event) {
return confirm('Confirm refresh');
};
In another part of the code, I am redirecting it to the page using window.location.href It returns a popup whether you want to leave the page. How can I avoid this popup when using window.location.href?
window.location.href = window.location.href.split('#')[0];
You could just set a variable to skip this behaviour :
let skipUnloadConfirm = false;
window.onbeforeunload = function(event) {
if(!skipUnloadConfirm) {
return confirm('Confirm refresh');
}
};
And then change value before setting href (function would replace direct window.location.href assignement and could be reused)
function redirect(url) {
skipUnloadConfirm = true;
window.location.href = url;
}
Or, you can override window.onbeforeunload before calling redirect
I want to get the access token in order to diaply the images of an account. So I display a pop up where the user can connect. The pop up works but it redirects to instagram site, with the user connected instead of send me the code. The link to the connection is something like :
https://www.instagram.com/accounts/login/?force_classic_login=&next=/oauth/authorize/%3Fclient_id=aaaaaaaa&redirect_uri=url&response_type=token
I log in and then, it redirects me to :
https://www.instagram.com/oauth/authorize/?client_id=aaaaaaa&redirect_uri=url&response_type=token
I don't understand how I can get the code. And I also used the exact same code as : https://github.com/radykal/instagram-popup-login
Can someone help me please ?
EDIT
var loc = window.location.host+window.location.pathname;
var accessToken = null; //the access token is required to make any endpoint calls, http://instagram.com/developer/endpoints/
var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) {
//the pop-up window size, change if you want
var popupWidth = 700,
popupHeight = 500,
popupLeft = (window.screen.width - popupWidth) / 2,
popupTop = (window.screen.height - popupHeight) / 2;
//the url needs to point to instagram_auth.php
var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+'');
popup.onload = function() {
//open authorize url in pop-up
if(window.location.hash.length == 0) {
popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self');
}
//an interval runs to get the access token from the pop-up
var interval = setInterval(function() {
try {
console.log(window.location);
//check if hash exists
if(popup.location.hash.length) {
//hash found, that includes the access token
clearInterval(interval);
accessToken = popup.location.hash.slice(14); //slice #access_token= from string
popup.close();
if(callback != undefined && typeof callback == 'function') callback();
}
}
catch(evt) {
//permission denied
console.log("error");
}
}, 100);
}
};
function login_callback() {
alert("You are successfully logged in! Access Token: "+accessToken);
}
function login() {
authenticateInstagram(
'16edb5c3bc05437594d69178f2aa646a', //instagram client ID
'localhost/facebook', //instagram redirect URI
login_callback //optional - a callback function
);
return false;
}
The code is ok, I think it is a problem with your app settings: Login to Instagram Developer, go to "Manage Client" and the "security" tab an disable "Implicit OAuth".
So I have a website that loads pages to a container div:
function goto(addr) {
$("#content").load(addr);
}
and a link that executes it
About us
My problem is that whenever the page is refreshed, the loaded content resets to the default page (page/home.php). How could I do so that it loads the previous displayed page?
Use local storage for example or sessions.
Local storage example:
$(document).ready(function() {
var lastPage = localStorage['lastPage'];
if (!lastPage) { // If user was on any url before we will exectue goto function
goto(lastPage)
}
function goto(addr) {
localStorage['lastPage'] = addr; // Set url to local storage before load page
$("#content").load(addr);
}
});
not only localStore but you need change the hash of url, and after do one function to catch hash code and execute at you "goto" function...
"something like that"
function hashnav(){
var hashfull = document.location.hash
var hash = hashfull.replace('#', '');
var $page = '';
goto(hash);
}
function changeHash($hash) {
window.location.hash = $hash;
}
function goto(addr) {
changeHash(addr);
}
$(window).bind( 'hashchange', function() {
hashnav();
return false;
});
I'm unable to work out where I'm going wrong with the following code.
My full url is http://localhost:4244/Invoice/PayInvoice?invoicenumber=7069 but var url = window.location.href; only returns http://localhost:4244/
<a Class="btn btn-success btn-sm confirm" href="/Invoice/PayInvoice?invoicenumber=7069">Pay Invoice</a>
Can anyone spot what I'm doing wrong
<script>
$(document).ready(function() {
$(".confirm").click(function (e) {
var url = window.location.href; // Returns full URL
alert(url);
$("#displayPopUp").show();
e.preventDefault();
$(".yesupdate").click(function () {
$("#displayPopUp").hide();
window.location = url;
//$(location).attr('href');
});
//if (AcceptPayment()) {
// // then redirect to original location
// window.location = this.href;
//}
//else {
// alert("Couldn't do my thing first");
//}
//var result = window.confirm("You are about to mark invoice as paid, are you sure?");
//if (result == false) {
// e.preventDefault();
//}
});
});
</script>
What I'm trying to do is pass the value of url to window.location = url; when .yesupdate is clicked
If you're trying to navigate to the href of the <a> element being clicked, you can retrieve that address within the .click() handler using:
var url = this.href;
The lines in your snippet just assign the current location back to itself, which will just reload the page.
var url = window.location.href;
window.location = url;
You may also need to remove previous click handlers from $(".yesupdate") to avoid them stacking from multiple .confirms.
You can use namespaces to target certain handlers.
$('.yesupdate').off('.confirm').on('click.confirm', function (e) {
// ...
});
You should not assign to window.location, it is a read-only instance of a Location object. Depending on your browser, this may or may not work or throw.
Instead, you should call window.location.assign(url) with the URL you would like to navigate to. You can use a full URL with query string and other parts.
//Gather AJAX links
var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
//Mark the recent state as null (because there is none yet)
var recentState = null;
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 500);
//Exit
return;
}
//Use AJAX for certain links
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
//Load the page state based on the URL
function loadStateFromURL() {
//If nothing has changed, exit
if (window.location.hash == recentState) {
return;
}
//Mark the recent state
recentState = window.location.hash;
//Go through an array of all AJAX links and check their IDs
for (var i = 0; i < ajaxLink.length; i++) {
//If we find a link's ID that matches the current state, load the relevant content
if ("#page=" + ajaxLink[i].id == window.location.hash) {
//Load contents into article.main
$("article.main").fadeOut(0).load(ajaxLink[i].href, function(response, status, xhr) {
//Show an error if the request fails
if (status == "error") {
$("article.main").load("./404.html");
window.location.hash = "page=404";
}
}).fadeIn(500);
//Update the page title
document.title = "\u2622 My Website Name \u2622 " + ajaxLink[i].text;
document.getElementById("headH2").textContent = ajaxLink[i].text;
//State has been fixed, exit
return;
}
}
}
This code works flawlessly when I run it locally!!!
But when I throw it on the web server my AJAX'd links will refresh the page when I first visit. However, if I use the back button then try the link again (or I'm assuming if the page is already in the browser cache), it will work properly.
I cannot allow this, because when people first visit my page the first link they click on will not operate as intended.
One of things I've also been testing is I'll bookmark my own site with a breadcrumb bookmark (example.com/#page=14) and see if it updates without my page already being in the browser cache. Again, it works on my local machine but not on my web server.
use event.preventDefault()
ajaxLink.click(function(e) {
e.preventDefault();
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
The issue maybe is that when you are applying your click event to these links, they may not be loaded to the DOM. So the possible solution is to put ajaxLink.click(function() { ... }); part inside window.load event or document.ready event. Since you have used window.load event, you can do something like this.
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 500);
//Use AJAX for certain links
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
//Exit
return;
}
Solved my own question, had to continuously parse the AJAX links to stay updated with the DOM as it changes.
First I put the ajaxLink declaration into a function:
//Gather AJAX links
function parseAjaxLinks() {
var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink");
return ajaxLink;
}
Then I had to put the ajaxLink click events into a function:
//Load the page state from an AJAX link click event
function loadStateFromClick() {
//Update the AJAX links
var ajaxLink = parseAjaxLinks();
ajaxLink.click(function() {
//Update the URL
window.location.hash = "page=" + $(this).attr("id");
//Load the page state based on the URL
loadStateFromURL();
//Return false or else page will refresh
return false;
});
}
Then I added a line in my window.onload event to keep my AJAX click events synchronized with the DOM (this adds overhead, but oh well):
//Initialize the page state based on the URL (bookmarking compatibility)
window.onload = function() {
//If no page state exists, assume the user is at index.html
if (window.location.hash == "") {
window.location.hash = "page=index";
recentState = window.location.hash;
}
//Load the page state based on the URL
loadStateFromURL();
//Keep the page state synchronized (back/forward button compatibility)
setInterval(loadStateFromURL, 250);
//Keep AJAX links synchronized (with DOM)
setInterval(loadStateFromClick, 250);
//Exit
return;
}
If you have a keen eye, you saw I had called the new parseAjaxLinks in my new loadStateFromClick function, so I added a line to the top of my loadStateFromURL function to keep the links updated in there as well:
//Load the page state based on the URL
function loadStateFromURL() {
//Update the AJAX links
var ajaxLink = parseAjaxLinks();
...
What I learned from this is the variables which are dependent on the DOM need to be continuously updated. While the DOM is loading, things are unpredictable and kind of sucks. **Drinks beer**