3

I have simple function;

    setTimeout(function(){ alert('hello');  
         //Business stuffs..
         location.reload();
         eval(localStorage.getItem('mysc'))},5000)

after open in a browser(chrome or firefox) I type this;

localStorage.setItem("mysc","setTimeout(function(){ 
    //Business stuffs...
    location.reload();
    eval(localStorage.getItem('mysc'))
    },5000)");

After that once I type;

eval(localStorage.getItem('mysc'))

I want this function executes in same browser window forever.. or till close the browser.. but as you guess, it only works once. How can I achieve this ?

12
  • setInterval(function() { eval(localStorage.getItem('mysc')) }) Commented Nov 30, 2016 at 18:19
  • @adeneo let me try it :) Commented Nov 30, 2016 at 18:20
  • you want first 5 sec wait then forever or call function every 5 sec ? Commented Nov 30, 2016 at 18:20
  • It's not really clear what you're doing, or why? Why would you store javascript in localstorage just to execute on the next reload ? Commented Nov 30, 2016 at 18:22
  • 2
    You can't execute javascript on the current page, even in a timeout, that keeps executing after a page reload, it's not possible. Commented Nov 30, 2016 at 19:28

1 Answer 1

2

You should create the timer on page load, and reload the page in the callback. When the page reloads, the timer will be re-created. This will "recursively" reload the page every 5 seconds.

<html>
  <head>
    <script type="text/javascript">
      console.log('page loaded, waiting...');
      setTimeout(function () {
        console.log('reloading');
        location.reload();
      }, 5000);
    </script>
  </head>
</html>


As far as I know, there is no way to achieve this if you don't control the page you want to reload (i.e., using Dev Tools or console APIs). It's impossible to attach a script to execute on the next page load, and any active timers are cleared when the current page unloads. A browser extension is probably the way to go; for example, Content Scripts can be used to achieve this in Chrome.

Sign up to request clarification or add additional context in comments.

8 Comments

vaiow it looks what I am looking for.. let me try
Note that you can't accomplish this from the dev tools, since you need a script to automatically execute on every page load.
yeah this is why I dont accept this.. because I need this work in console..
I need find a way trig this iteration in dev console
Please update your question with this requirement. This will probably require hooking into some console API, and if it even exists, it will be different for every browser. This is a job for a browser extension, not a console script.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.