Warm tip: This article is reproduced from serverfault.com, please click

Redirection only if the button is clicked on the previous page

发布于 2020-11-26 23:06:12

I'm trying to achieve redirection only if the button is clicked on the previous page. I'm new to JS, so please be gentle.

For example:
When the users come on login page they have this button:

<button type="submit" class="form-login-submit" name="login" value="Log in">Log in</button>

When you click on Log in button you will be redirected to the My Account page which contains this class member-logged-in in body.

So, this is my code:

const logInBtn = document.querySelector('.form-login-submit');

logInBtn.addEventListener('click', () => {
  window.onload = () => document.body.classList.contains('member-logged-in') ? window.location.href = 'www.test.com' : '';
});

But when the user is redirected to the My Account page I'm getting this error, I think because the Log in button is missing on that page:

Uncaught TypeError: Cannot read property 'addEventListener' of null at (index):691

Any help is appreciated.

Questioner
Marko
Viewed
0
upss1988 2020-12-02 02:57:44

You can solve this using localStorage. Maybe it's dirty solution but it will work.

const logInBtn = document.querySelector('.form-login-submit');
const isPage = window.document.href = 'https://test.com/my-account/';

logInBtn ? logInBtn.addEventListener('click', () => localStorage.setItem('justLogin', 1)) : 0;

if (isPage == 'https://test.com/my-account/' && localStorage.getItem('justLogin') && document.body.classList.contains('member-logged-in')) {
    localStorage.removeItem('justLogin');
    window.location.href = 'https://test.com/members/';
}