rogerlsmith
rogerlsmith

Reputation: 6786

How to run a javascript function when ANY page is loaded

I am doing some maintenance work to a fairly large existing site written in PHP & JavaScript. I am trying to set up a "time out" so that the user is automatically logged out after a specified period of time. I think I have the code that will "expire" the users session, but what I need is a way to run a specific javascript function whenever ANY of the pages in the existing system are loaded. I'd rather not manually add a call in each page as this would take forever and would require even more testing.

Is there a way to add a javascript function call to the window or some other part of the DOM to get called whenever a page is loaded?

Thanks for any help!

Upvotes: 0

Views: 173

Answers (4)

tuze
tuze

Reputation: 1978

That depends to your site script. If you're checking your session data on every request this could be done easily.

Add time data for a session's last move, append it to a js script which controls that If it's time to end the session or not. And take action(js redirect or an ajax request)

Upvotes: 0

tkone
tkone

Reputation: 22738

No.

You have to have the javascript function load into every page. But you just have to write it once and then include like:

<script src="logout.js"></script>

and then you'll need to set the timer for the logout

<body onload="setLogoutTimer()">

But in order for every page to have it you either need to explicitly place it in every page.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78550

Write the javascript in a .js file, host it on your server, and link to the .js from all the pages. While this does not apply a global rule, it is the only way I can think of and it won't be a problem for testing as the code will be from one source.

Upvotes: 0

Dominic Goulet
Dominic Goulet

Reputation: 8113

There are many ways to achieve this. BUT, you will have to first include a reference to the javascript file.

Then, you can, for instance, use jQuery to detect that the DOM is loaded and ready to call a function of yours.

On a side note, can I ask you why you need to call a javascript function? There are probably other ways to do that, like a listener on your server that redirects to a logout page when a session expires.

Upvotes: 2

Related Questions