Force all execution to pause using Javascript - javascript

I am making a chrome extension that aims to pause execution of a tab if it inactive after some time in order to stop if from consuming resources.
By "Pause", I mean something like debugger, however, debugger does not seem to work unless the developer inspector tool is open.
Is there anyway to stop a tab from consuming resources until the user goes to that tab and click on something (like the play button on debugger)
PS: I want to make this because there a synonym/dictionary website that slowly consumes 5GB of RAM even if it is left inactive for half an hour.

The only way is using alert() or prompt(). Enter may be used to confirm and continue executing.

Chrome extension has API for this.
Tab discard
chrome.tabs.discard(
tabId?: number,
callback?: function,
)
Add permission tabs if required.

Related

How to debug a tab in Google Chrome that freezes right from the browser start?

In a vue web application, I have the issue that I have some deep links (example.com/app/some/123) that are handled by the application (vue-router).
Sometimes (not always), for whatever reason when clicking such a link (in Outlook or from a desktop shortcut) when no browser window is opened, Chrome starts but immediately freezes (tab becomes unresponsive).
It feels like there is some redirect loop going on in my application code that causes this freeze. But my issue is that I have no clue on how to debug this to find the spot:
Opening the devtools is possible using the menu but JS files/code does not "load" - Scripts tab stays empty
Clicking the pause button does nothing, the same applies to pressing F8 (pause script execution)
The profiler cannot start (stays at "initializing").
I also have the feeling that this happens when a new version of the app (js bundle) is published but Chrome has some previous version cached. It feels this more often produces the issue. But this is just a guess.
Clicking the pause button/F8 is my regular procedure to tackle such things to find the spot where we are in the JS code at the moment. But unfortunately, here, this does not work as most of the browser is unresponsive.
The only way to close Chrome is to kill it via the task manager.
Is there any way to enable additional logging via Chrome settings or activate an "immediate debug session" right when the browser process starts to somehow get closer to the JS code that freezes the whole tab?
So ideally that somehow, right from the browser start, a profile of the "debug session" is saved even if the browser is process-killed that can later be inspected?
You could try webQsee (https://chrome.google.com/webstore/detail/webqsee-web-sniffer-recor/gamdpfnfkjknkimfbboonmgdfnondfme). The extension provides some usefull export features that might help you identifying the root cause.
Event Snapshot
Exports Screenshot, Cookies, Network and Console output. A lot of info but it is a proprietary format, in can only be analysed in the extension itself.
Excel Export
Like an HAR export, but also including Console output.
These two export options (and more) are available via the export menu located at the bottom of the extension window.

Chrome devtools: Drop into debugger without switching to Sources tab

If I put the debugger statement in my JavaScript source with the Chrome devtools open, it'll stop execution so I can interactively explore the current context from the console. It's really awesome.
But unfortunately it will also switch to the Sources tab and display the line where the debugger statement happened. Most of the time, I want to type JavaScript commands, so I have to manually switch back to the Console tab.
Can I avoid the tab-switching and stay in the Console tab?
Or am I using it wrong?
Right-click on the source-tab and select 'move to bottom'.
Looks like Chrome added a preference for this in the intervening 9 years: https://stackoverflow.com/a/69216922/66673
Quoting that answer:
I had the same issue and it was driving me nuts! The way I managed it to stop switching was to go to into the DevTools settings -> Preferences.
Under Sources options, uncheck Focus Sources panel when triggering a breakpoint.
There's a reason for that - and is that whenever the code has stopped, because of a breakpoint or a debugger statement, you'd usually want to actually see where the execution has stopped. So, the developer tools switches to the Scripts/Sources tab, and this is a common behaviour among the major browsers, that may also show the local variables, the call stack and so on.
The best thing you can do is to keep the console frame always open, so you're ready to work. Just press Esc or click on the second icon on the lower left corner. That's what I usually do.
Switch to the Console tab when you expect to get a large response from the command you type.

Does IE go into sleep mode?

I have this functionality built in Jquery/ javascript where a user is notified when their session is about to be timed out. Then they are given an option to extend it. If they don't make a choice the pop up closes itself and the browser is redirected to the login page. It worked perfectly fine for a while. But now I noticed it works correctly only if I am active on the computer. If the computer is left unattended for an entire day, the pop up does not begin the countdown until the user unlocks the computer and logs in again.
Is anybody aware of this behavior where ie stops executing javascript when the computer is left unattended for a long time?
Update: Is there a way to keep the tab from sleeping? Without that, the browser won't be able to redirect at the right time.
setTimeout only works when the tab is active. In some browsers even changing tab will make it stop counting. So not only if you are on the computer but if you're not on the specific page it might not work. Also on mobile devices with multitasking it's bound to fail, forget about tabs, applications often go to suspended mode.
Take a look at this question, it offers the same solution as Luka with a code example:
How can I make setInterval also work when a tab is inactive in Chrome?
You might want to do two checks on the time passed, one to check if you need to show the popup, and one to close the popup, using the total time passed instead of having a different count down.
i would suggest logging the current time when the page is loaded and then calling a function every 10 seconds of so that checks if the time passed is more than x amount, the reason your problem occurs is most likely because the default timeout function only counts down while the page is being rendered.

Long running task in a google chrome extension

I have some operations (basically create new folders and links), which can take several minutes. Now the problem is that in this time chrome does somehow block such that i barely can use the browser (in the "check popup-mode"), which is bad. In addition my spinner gif does not spin. ^^
Besides that the operation is aborted if I click on another tab or so (which closes the extension) in the normal mode, which is also bad.
Does anyone have some ideas to handle these cases?
You'll do the long-running tasks in a background page. To notify the background page from the popup when to start the task, you can use message passing. Since the background page is always open, it will not stop running when you navigate away from the popup.

How do you stop an infinite loop in Javascript?

Let's say I accidentally wrote this:
do { } while (true);
...and then ran it. Apart from killing your browser, is there a way to stop javascript execution (the equivalent of Ctrl+Break in basic, or Ctrl+C)?
Normally, after about 30 seconds your browser asks if you want to stop the long-running script, but this doesn't always happen (as I just found out)!
FYI: A simple loop such as this: for (i=1; i > 0; ++i); will cause my browser to crash (Firefox 3.5b4). I don't feel much like testing to see if it's any of my add-ons. Continuously restarting my browser isn't my idea of a fun Monday night.
2018 update:
In Chrome 67, if you have the DevTools open (F12), you can end the infinite loop without killing the whole tab:
Go to the Sources panel and click "Pause script execution".
Hold that same button and now select the "Stop" icon.
https://developers.google.com/web/updates/2018/04/devtools#stop
I'm using Chome Version 45.0.2454.101
At the top right hand corner, at the hamburger menu, click on More Tools > Task Manager, and then kill the tab from there. This is if attempting to close the tab fails. Otherwise a simple 'X' on the tab kills it.
At least with Chrome, you may be able to kill off the individual tab and not the whole application.
Randolpho has also informed me that IE8 has similar functionality.
If you are using Chrome you can easily kill not responding tab:
Switch to any other tab
Press Shift + Esc to open Chrome's Task Manager
Find your tab in the list (Should be the most memory consumer)
Click End Process
Important: Navigating to another tab is important, because if you are on the original tab JavaScript will make the browser unable to process your key press and do nothing because of its infinite loop.
ref: https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox
Firefox is particularly problematic ...
Warning! Caveat! Do NOT run this!
javascript:
while (true) alert("irritated and exhausted - yet?");
This will go "infinite" and will NOT exhaust an internal timeout since the script will not chew up CPU time fast enough. In FF 11 this guarantees there will be no "unresponsive script" abortion opportunities.
Gracefully stopping just the offending script was possible and trivial in early browser versions, using manual intervention, without croaking and aborting the whole browser. To not have such control is a major browser software design flaw. Unreasonable dexterity and reflex are required to effect the manual motor mechanics of the "solutions" described in the reference.
Caveat: It is possible for scripts to go "infinite" w/o timing out AND w/o alert type prompts. These are particularly pernicious and annoying. Basically, the scripts run slowly enough so that the CPU time cycle allotment of say 20 sec. is stretched out over several minutes or hours or ..., before timing out, by suspension of execution pending resumption on an event trigger. Instead of timing CPU cycles it would be far better for scripts to timeout on real world clocking. (Ever notice how you cannot abort a script that is trying to retrieve content - but unsuccessfully - for constructing a page? In FF both the address bar buttons reload and cancel/stop are disabled though the tab at least can be closed.) Normal javascript Timeout() and setInterval() calls do not suffer from this and are conditioned so that while suspended, manual intervention is possible to abort them "gracefully".
Test environment for empirical observations:
window.navigator.userAgent=
Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0
PS. the script
for (i=1; i > 0; ++i);
will eventually trap on an overflow error when i exceeds the maximum value allowed.
Most browsers have a "slow script performance" warning that comes up when an out of control javascript is taking a very long time to execute. This warning dialog usually gives the option to kill the offending script.
Depends on the browser. Some let you click the "stop" button to stop javascript execution. Others don't.
I suggest the best way is to just kill the browser or tab entirely.
In Firefox
Go to Developer Tools > Debugger, and click pause button.
In Chrome
Go to Developer Tools > Sources, and click pause button.
most decent browsers do show an "unresponsive script" warning... If not, I guess your best course of action would be to find out why the warning is not popping up.
From https://superuser.com/questions/92617/stop-never-ending-popup-alerts-in-firefox#comment93927_92617, by anonymous:
This isn't a satisfactory general-purpose solution, but with Greasmonkey (or maybe Ubiquity or Jetpack) you could overwrite window.alert with a function that calls window.confirm and optionally throw(s) an error, stopping all script execution, or toggles a flag to stop alerts. That might be useful if a site you keep going back to presents this behavior.
What I do when using Chrome and this happens is hitting shift+ctrl+esc to bring up the windows taskmanager. Then switch to the processes-tab and scroll through the chrome.exe processes(chrome has one process for each open tab) till I find one with significantly higher cpu usage than the oters. It tends to have around 30% for me while all others have like 0-2%
Then I'll just end that process.
Actually the same can be done by going to tools>taskmanager or shift+esc in chrome to open its custom taskmanager for its processes. Might be easier to use that since it shows more info of the tabs.
Last resort: close the browser from the OS. I had good results closing Chrome from the taskbar in Windows 10 while an infinite loop ran. If that didn't work I would have killed the browser in Task Manager as above. On other OS's, of course the exact technique would vary.
Infinite recursions are less a problem. All systems I've seen limit the size of the execution stack, and interrupt with a runtime error eventually once infinite recursion leads to stack overflow (no pun intended).

Categories

Resources