Modify URL before page-reload - javascript

I have an area on my site, where user can login directly with a secret link. He then is been redirected through my framework to the final view.
Now when the session dies, and the user reloads, I need to point the actual reload to the initial secret link (which the frontend knows) to get a new session and avoid the login-screen.
I tried:
<script type="text/javascript">
$(document).ready(function() {
window.onbeforeunload = function() {
// on reload: redirect to direct-login url, to ignore dead session
window.onbeforeunload = false;
window.location.href=$('base').attr('href') + '/users/directLogin/<?=$_SESSION['Auth']['User']['secret_token']?>';
}
});
</script>
From this code I'd expect to reload another URL when the user triggers page-refresh, but it keeps reloading the same url as is.
To point out the problem: If the user keeps on that final page when refreshing with a dead session, he will be thrown back to a login screen. To avoid this and give a feeling of "out-of-the-box-area" while inside the box, this concept is what I came up.
EDIT:
This approach is not possible. To anyone having a similar concept to achieve: A synchronous ajax would prevent the page from reloading, until the ajax finished. This way you could easily generate a session before reloading. You may consider yourself if this is a good solution for your project. It fit mines but someone might say this is evil.

Related

How to skip external redirection page using history back function?

Let's say an external site has a redirection page before actually moving to the internal site when user clicks the link.
This internal site only has a button that will let you go back using
History.back() or .go(-x). I can only do changes on the internal site.
What's happening here is that we now have a "loop" that redirects to the external redirection page using history.back(), and then the user will be redirected once again to the internal site.
Flow:
External site -> user clicks on internal site link -> external site sends user to external redirection page -> user redirects to visit the internal site -> user click history.back button -> user get redirected to external redirection page -> user redirects to visit the internal site again
I basically do not want the user to end up at the internal site after users clicks the history.back button.
I thought about saving page visit in localstorage, so that if it gets redirected back to the internal site again it will instead do history.go(-2).
I am also aware of https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer document.referrer, but that will also degrade the UX since the user gets redirected back and forth at least once.
The only solution I could think of is having a query parameter upon visiting the internal site someurl.com/?redirects=2, so that we could do history.go(-redirects). However, that requires the external site to decide how many redirects it has.
Is it possible to know if user comes from a redirection page from the external site? Is there a way so that we can skip the external redirection page and just go straight to the external page?
window.location.replace is there for exactly the same requirement, please refer https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
Assuming that the external rediection page contains only the logic for rediection and no content, they should have used location.replace for redirection to have a clean state of history.
I know that you do not have control over external site but I just wanted to help in case you can ask someone to make changes there :)
I came up with a solution to the problem, but my approach does use document.referrer.
Regarding UX degradation when using document.referrer, it should be barely noticeable as long as your clientside code is optimized.
Also, you might be interested to read this MDN Article.
My solution approach is attached here:
const isExternalURL = (url) => new URL(url).origin !== location.origin;
function checkExternalURL() {
const referrerPage = document.referrer;
if (referrerPage == undefined) return false;
return isExternalURL(referrerPage);
}
if (checkExternalURL()) {
console.log("External URL Detected");
} else {
console.log("Internal URL Detected");
}

location.replace() doesn't replace the page

I'm experimenting for the first time with transition between html pages. I've been looking for the differences between replace and a href when I founded them I chose the second one. I'm building a sign-out button. So when i click on it I need to be redirected to the login page. But I also need to make impossible for the user to navigate back to the home (from the login) with the back button. So in my home.js file I wrote that (I'am working with firebase):
const disconnettitiButton = document.getElementById("disconnettiti");
disconnettitiButton.addEventListener('click', () => {
firebase.auth().signOut().then(function() {
// Sign-out successful.
window.location.replace("../index.html");
}).catch(function(error) {
// An error happened.
});
});
while this is the html corresponding to the button (It's not really a button...)
<a class="nav-link" href="#" id="disconnettiti">Disconnettiti<span class="sr-only"></span></a>
The problem is: The window.location.replace() succeeds in changing the page and returning back to the login form. But when i click the back button I can also return to the home page, where i called the .replace() function. The replace method should delete the top of the history but this is not the case. Any solutions? Many thanks
There is a basic error in your logic. Restricted area pages should be accessible only with valid grants.
These grants should be deleted when user logs out. So even if you press the back button you don't have the grants anymore and you are redirected to the login page. The same will happen if you try to point to a specific url in the restricted area.
You can use a cookie for example that you set/unset on login/logout or you can use sessions. On each page in the restricted area you need to have the check of the existence of the cookie at the beginning and otherwise the redirect.
Something is working wrong in your application if after logout you can still see things that are inside the restricted area (but you didn't provide code to check that)
EDIT: i saw #scragar comment after i posted my answer but I fully agree with that and not with OP's answer. There are no need for a login page if you don't want to restrict the application. The login becomes completely meaningless if you can access restricted areas anyway
I think you need to give complete url rather than giving a relative path. So if you are serving the page from localhost at port 3000 and index.html is at root, then you should give the path as http://localhost/index.html.
Also, your script must be throwing an error. You should check the browser console first, if something doesn't work.
Hope it helps:)

Prevent main page from flashing before login-page redirect

I feel like the solution will be simple. At least, I hope so.
I've got index.html, which is my main page, and the first thing it checks is whether or not the user is logged in or not.
var currentUser = Parse.User.current();
if (currentUser) {
} else {
window.location = "login";
}
If the user isn't logged in, then he/she is redirected to the login page. The problem is that the main page flashes for a quick second before redirection. Of course, I understand that this is because checking whether or not the user is logged in takes just enough time to show the page for a split second.
What's the best way to solve this? The ways I've thought of would probably still flash a page. (Turning the login page into index.html would probably flash the login page for a second).
Output buffering ob_start()
Also, the session status should be checked server-side before generating output in order to reduce server load and improve smoothness of operation.
EDIT:
I do assume a server-side script handles your user sessions.

Remove POST data when using custom javascript back button

I've coded some custom navigation buttons into the project I'm working on, via javascript - they essentially copy the browser button functionality (brief wasn't initially clear on why separate buttons were required, but they asked for them):
function goBack() { window.history.back(); }
function goForward() { window.history.forward(); }
However, as the functionality is the same as the browser back button, the website asks if I want to resubmit POST data if I go back to a page with said POST data, which is undesirable. Ideally, to fit with the current site setup (all POSTs submit to the originating page, which checks for POST data and performs the relevant submissions to the database), I want to clear the POST data so there is no request to resubmit.
I'm not familiar with the Post/Redirect/Get (PRG) that people might recommend, and it doesn't seem to cover the concept of continually pressing "back"; if you submit a form, you post to a page which handles the post action, then redirects to a GET page - but the redirect is still in the history, meaning if you go back, surely you would hit the redirect page and just be sent "forward"? Plus, PRG seems mostly centred on page refreshing, which is not what I'm looking for at the moment.
The concept of PRG also seems to be due to the browser back button not allowing for additional code to control POST data, so coders have to make the best of what they can access.
With my relative freedom of having a custom back button which could allow for manipulation of POST/session/cookie data, I'd consider there should be some method of calling a global session variable or cookie on back button press, which then gets picked up on the previous page load to unset the POST data and the global session variable/cookie, but my attempts to implement something like this have not succeeded - they've been simple single-line setcookie('back', true) or set($_SESSION['back']=true) PHP snippets within goBack(), with PHP earlier in the page:
<?php if (isset([either set cookie or set session variable]) {
unset([either set cookie or set session variable]); // also tried changing 'true' to 'false' here
unset($_POST);
}?>
Is this kind of behaviour possible and I'm just looking at this from the wrong angle, or is the only way to do a successful back action while suppressing POST to re-engineer the site to use PRG, which will be comparatively significant legwork? Is there some other point in a page load/POST submit that would allow for clearing the POST data, to allow for the back button functionality I'm looking for?
EDIT
I, as an example, navigate to site.com/stuff/edit/[an ID], to edit an item of stuff. The first time I visit, there is no POST data, so the PHP check of isset($_POST) returns false and the page is simply rendered with a form which is populated by a GET.
I amend in the form and press submit. The submit sends the POST data to the target page; this is STILL site.com/stuff/edit/[an ID]! However, because there is now POST data, the PHP picks this up, validates it on the page (you'll see why later) and performs backend model and controller functions to update the item to the database serving the site.
Depending on whether the update was successful, the page then renders the form again, with the information which is retrieved from a GET, which pulls the information from the server (amended or otherwise) and either a success or fail message.
If I want to add a new item, I navigate to site.com/stuff/new; this navigates to the same page as site.com/stuff/edit, but PHP code determines the masking URL and renders different aspects of the code to look like a different page with a different POST action - it also notes there is no ID passed in.
I add an item, and the POST redirects back to the same page; this time, though, there is no Id from the server, meaning the code behind picks up the fact it is a new entry, and performs an insert. It then either displays a success message with a link to view/edit the new item, or a failure message with a prepopulated form to reduce retyping the new item into the form.
I hope this has helped show how this page works; its not necessarily how I would have written the site, but I've inherited the work from an ongoing situation and work with others who code in this way, so I need to be consistent or make unobtrusive changes rather than radical redesigns of in-use code.
I think this should do the job:
function goBack() {
var referrer = document.referrer;
if(referrer != '') {
window.location = referrer;
} else {
window.history.back();
}
}

Document.referrer wrong when pressing the back button

I have a PHP / Javascript page that automatically logs a user into different systems from one log on. These are external sites and all works good except when the user hits the back button. It then redirects them right back where they came from.
I'm looking to have it redirect back to my main website and avoid getting stuck in this redirect nightmare. So I tried document.referrer, but that only seems to grab the current page I'm on and not the referred site. Am I wrong or can this not be done like this?
function myfunc () {
var frm = document.getElementById("loggedin1");
if(document.referrer != 'https://someurl') {
alert(document.referrer);//Just used to see output
frm.submit();
}
}
window.onload = myfunc;
If I could get it to function I would add an else in there and have it going back to my website.
Thanks!
It sounds like you are trying to go back to a previous page, that is not within the website of the page you're on?
A few points:
1) document.referrer will only work if the person got to the current page through a link, or clicking something.... not if they were redirected through other means.
2) Due to browser security implementations, you will not be able to access the javascript history for other sites. So if you go from your site, site A, to site B for a login, you will not be able to access the site A history from site B.
If you need to take them back to the previous page they were on on your site, can you use an iframe to load the external page? that way they'll never leave your site? Or maybe a window popup?
If what you are trying to accomplish is site logins, have you looked into the available apis? Sites like facebooks have apis for allowing logging in on your site through theirs.
Cheers!

Categories