Keep the console script persistent in Google Chrom

2019-07-22 12:22发布

问题:

I have a script I want to use in the Google Chrome console. But this script is going to reload the page. A bit like this :

setInterval(function(){location.reload();},3000);

The problem is, once it's reloaded, the script stops and the console is cleared. I tried the option "Preserve log on navigation" : it preserves the log, but the script doesn't restart after reloading.

How should I do ? Thanks :)

回答1:

There is no way to actually do that. The only possible way I found is to develop a Chrome' extension and place your script on it. Your script will be excecuted every time the target page is loaded, so when you execute the location.refresh() method , the next time the page is loaded your script will be executed all again and so on. If you wish to persist some data between page loads, then you can use localStorage.


Find more information here https://developer.chrome.com/extensions/getstarted
How to inject scripts via extensions ?: https://developer.chrome.com/extensions/content_scripts

remember that the scope of the extensions is isolated from the rest of the page, so you cant directly access JS variables or functions declared in the page itself from an extension BUT you can interact with the DOM. Good luck



回答2:

I am using a cool Chrome Extension called Resource Override, which allows you to inject a script on specific urls. So all you have to do is put your url (with * on each end), and create a JS file injected into the HEAD, and it will be ran every time. You start from scratch on every page though, so I'm not sure how you can persist data. Maybe in cookies?



回答3:

Try creating a parent html document that has an iframe whose source is the original html page. Place the javascript in the parent html page and tell it to reload the iframe.