How do I run additional JS function after calling location.reload()? - javascript

I am trying to run some code that refreshes the webpage, and THEN does the console log.
The issue is the console.log is happening before the page reload.
location.reload();
console.log("test");
How do I adjust this to get the desired behavior?

The very act of refreshing a web page ends execution of scripts on that page, apart from what might be called in onbeforeunload or onunload handlers. Once the reload has actually occurred, no more JavaScript in the pre-reload page can be executed.
If you need to cause something to happen after content has been reloaded, you'll have to use something like a cookie to pass a message to the reloaded page indicating the action you want to take.

Use extentions like TamperMonkey to handle your script.

Related

window.onload not triggered when user navigates but does when refreshing the page

I have a Chrome extension with a content script that must be injected when the url matches the rule. the thing is, if I refresh the page, it's working, but if I navigate to the url (it does match the pattern) then the event is not triggered.
Any idea why?
Edit: Take into account that it's based on a web app and I've tried using the webNavigation event and still doesn't work.
Edit: Ok, so a working solution (in Chrome at least) is to use the onHistoryStateUpdated event handler.
Possibly due to the cache saved in your Browser. If you hard refresh it, then it will run the whole script again.
You can use the following code:
$(window).bind("load", function() {
// code here
});
You can also try this function:
window.onpageshow()

Stopping JavaScript code execution immediately after a redirect in Chrome DevTools

I've got a scenario where a user receives a round-trip redirect via query string from one site to another.
For instance, the user starts on example-site-a.com, gets redirected to example-site-b.com?redirectBackTo=example-site-a.com, and is redirected back to the original site by setting the window.location.href to the query string value.
I would like to debug/step through JavaScript located on the second site, but the second redirect happens in the blink of an eye.
Say my JavaScript on example-site-b.com looks like this:
<script>
alert("debug!");
debugger;
console.log("test");
</script>
alert() doesn't pause the code execution and debugger isn't working either. I also tried setting an Event Listener Breakpoint in Chrome DevTools to pause on Script First Statement, but the console.log statement is still eluding me.
I'm just looking to step through the above code on example-site-b. Any ideas?
alex said that this suggestion from Shilly did the trick:
What is causing this redirect? WIll it wait for all JS to have stopped running? In that case you can use a setTimeout so you have time to press the F12 button. If the redirect will happen serverside or will not wait for JS in site-b to finish, you'll have to remove the redirect mechanism for a bit and just do a manual redirect to site-b to test.

Get a bookmark to load a page and run javascript on it [duplicate]

I have a bookmark that opens my a google calendar page (http://www.google.com/calendar/renderOnline) and a bookmarklet that applies some javascript on it:
javascript:document.getElementById('gadgetcell').setAttribute('style','width:300px');document.getElementsByClassName('sn-frame')[0].setAttribute('style','width:300px');
Is there a way to combine these into a single bookmarklet so that i don't have to click twice all the time?
Thank you!
No. A bookmarklet runs in the context of the original page, so it can't change pages and keep running. You may find GreaseMonkey helpful if you always want to run that code on the page. Or, Stylish lets you apply user styles to pages.
You could use an extension to get the same behavior.
For example in Safari you would create a button that launches the URL and an injected script that runs your bookmarklet. GreaseMonkey and many other extensions frameworks can do similar things.
I had the thought to use a bookmarklet to do this:
javascript:location.href='http://google.com';setTimeout(function(){alert('hi');},2000);
The setTimeout function could be anything, and due to the 2 second timer, the page would have time to load and the arbitrary code would execute against it. But it didn't work. No matter what function I seem to try to call in the setTimeout, it just never executes, or perhaps it executes in some other space that was being destroyed as the new page loaded or something like that. That setTimeout code works fine as a bookmarklet as long as there's no location.href change, it seems.
However I wonder if perhaps a better approach would be to do an AJAX load of the page you want into the current space, and then try to execute something. If I get around to trying that I'll update here.

Why does `alert("2nd");` execute before `window.history.back();`?

When I ran the following two JavaScript commands...
> window.history.back(); alert("2nd");
...I was expecting the window to go to the previous page, and then display the alert. What happens is "2nd" actually pops up first, and then the window goes back. If I reverse them like this...
> alert("2nd"); window.history.back();
...the commands still execute in the same order. What don't I understand about JavaScript control flow? How would I get window.history.back(); to run first?
Well, it makes sense that the alert is not displayed after the other page has loaded. The script is part of the loaded page, so if that would work, it would mean you could inject javascript in the previous page, which is of course undesirable.
So as I see it, there are 3 possibilities:
The back function is blocking and works immediately, navigating to a previous page, and terminate the running script. This obviously isn't happening, otherwise you wouldn't get the alert at all.
The back function works immediately, but the script is only terminated when the browser has enough information to start loading the other document. This doesn't seem to be the case. If it were, the browser would probably load the document in the background while the alert is open, but that doesn't happen.
The back function just signals the browser to go back, and the script keeps running until it's idle before that request is actually fulfilled. This seems to be the case. Navigation only starts when the alert is closed and the script ends. (At least in Chrome).
Anyway, if you want this to work, you'll have to call alert from the page you are navigating to.
Control has to be given back to the browser before back is actually executed. It just tells the page when you get a chance, go back.
Once control is return the browser unloading hooks are called (onbeforeunload, onunload, browser specific events).

How to tell when location.reload() has finished refreshing the page?

I am using location.reload() in a script
and I want to run another script when the reload() function has finished.
Are there any events associated with reload()?
All the scripts on the previous page are long gone by the time the page reloads. Therefore, there is no way to tell from the script that ran .reload() that the page has fully loaded.
Unless:
You work with an iframe, where you can reload just the iframe and listen for load events from outside the frame. That way, the script that listens to it is preserved.
Or, have the page contain an onload as suggested. However, the previous code, values and all are long gone as you just reloaded the page.
You might be solving the problem at the wrong angle as well. Instead of having the script, with all it's values, persist across page changes, why not make the data persist across page changes and read them upon every page? In this case, localStorage or cookies is your friend.

Categories

Resources