Executing a JavaScript function only once even though it matches all pages?

I have a code that works on all pages on a site, example.com. I run it with Greasemonkey/Tampermonkey.

The code checks if I was logged in. If I wasn’t, I am being moved via window.location.href to:

example.com/signin

The problem is that this code creates an endless loop of moving the user to the signin page, because it works in the signin page as well.

A possible solution is make the code to run on all pages but the signin page, but I do wonder if there are other, possible approaches.

As a newcomer, I know none.

methinks the easiest solution is to not include the JS file on the sign-in page, assuming that you have a server-side language that creates the pages.

Dor I edited the question to emphasis that I’m the one who runs the script on all pages of the site via Greasemonkey/Tampermonkey. It might change the answer (which I didn’t understand).

I’m not too familiar with Greasemonkey, but ain’t there a filter that tells the browser on which pages it should run?

Not that I know of. This does’t seem to work (at the meantime I search for a solution):

// @match        https://teamtreehouse.com/*

function loginToTreehouse () {
    if ( !document.body.classList.contains("logged-in") ) {
        if ( window.location.href != "https://teamtreehouse.com/signin?return_to=%2F" ) {
                window.location.href = "https://teamtreehouse.com/signin?return_to=%2F";
        }

I guess you could write script to deal with location.

But I think it should be easier to have a more specific exclude in the metadata eg.

// @include http://example.com/*
// @exclude http://example.com/login

see https://wiki.greasespot.net/Include_and_exclude_rules

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.