How to run function after press F5 (refresh)? - javascript

I tried to make some script that handle with event like "panel changes follow by URLhash". I had no problem with event on button or link but I had problem when I refreshed the page. My panel couldn't keep its values and automatically reset.
And I tried to solve refresh problem like this:
<script>
document.addEventListener('keydown', function(e) {
if(e.which == 116) {
window.alert("1234");
var id = window.location.hash;
changePanel(id);
}
}, false);
</script>
As code I shown you, alert() function it was working, but changePanel() wasn't working. I think because alert() had ran before refreshed and changePanel() also. But in case of changePanel() it ran before refresh then after refreshed all changes are reset to default.
How to run changePanel() after refresh?

It will not work, because after press of f5 page will be refreshed so new content will come on page, and so your panel/tab is reset..
You can try your code on
$(document).ready(
var id = window.location.hash;
changePanel(id);
);
Above code will automatically set tab after refresh button, and you can keep same code of that 2 lines on your button press, so that will work for your live page too. :)
This will work for you.
Thanks.

It works perfectly for me.
Call the funtion from your html
<button type="button" name="button" onclick="loro()">fdthd</button>
JS file
function loro() {
location.reload();
localStorage.setItem("po", "momo");
}
$(window).on("load", function() {
if (localStorage.getItem("po") === "momo" ) {
alert('Bien, ejecutaste el boton')
localStorage.setItem("po", "lulu");
} else {
alert('No has precionado el boton')
}
});
Before refresh the page I run a Function to save the "momo" value in the "po"key
After that, I refresh the page and check if PO has the value of momo. Depending on if I run the function before the refresh, it will run a specific alert.

Related

How to make JavaScript Snippets work after page reloads, in Chrome?

Environment: Chrome, a simple Web Portal
I'm trying to do a simple browser automation.
In a HTML table, 1. Clicks the first link, 2. Change the dropdown value and 3. click Submit.
The code after button click is not executed, as the page loads after the button click.
var tbl = document.getElementById("incident_table")
tbl.rows[2].cells[2].getElementsbyClassName("linked")[0].click()
// below code is not executing, as the above click loads the page
document.getElementById("incident.state").selectedIndex = 1
document.getElementById("sysverb_update").click()
I can able to run the last 2 lines of code separately in console, it works.
But when executing as a snippet it didnt
this post is very similar to your question:
preventDefault() on an <a> tag
what you want to do is prevent the default action of the javascript click event.
What you may also do is:
tbl.rows[2].cells[2].getElementsbyClassName("linked")[0].addEventListener('click', ()=>{
preventDefault();
//write here what should happen instead
});
What this will do is prevent the default action "reload site" from happening
Edit:
What i mean in the comment is the following:
if(localStorage.getItem("firstPartComplete") === null){
//do first part
//set completion status in localStorage
localStorage.setItem("firstPartComplete", true);
}else{
// do second part
localStorage.removeItem("firstPartComplete");
}

window.stop method does not seem to work when used within a function

So ive been wracking my brains with this for a while but can't figure out why this isnt working.
Im setting up some simple functionality to prevent a user from leaving a page via hyperlink and instead displaying an overlay. So ive set up a simple event listener on all links which when clicked will stop page load and fire up the overlay.
The mmClickRecieved variable is for another part of the script and is just to ensure a user only ever sees this overlay once. The timeout function will fire the same overlay if the user is inactive on page for a certain period of time.
However when i try this code, when clicking a hyperlink the overlay fires fine but the page does not stop loading. Ive tried various bits of this code in isolation and it all seems fine, cant quite figure out why this is not working. Any ideas anyone?
$("a").click(function() {
if (mmClickRecieved === false) {
if (navigator.appName == "Microsoft Internet Explorer") {
window.document.execCommand('Stop');
}
else {
window.stop();
}
clearTimeout(mmTimeout);
mmNumberOverlay();
}
else {
// no further action
}
})
update: not sure why ive got a -1 for this.. I can update the question if it doesnt make sense
Why not use preventDefault - it stops the user from following the link that was clicked and instead allows you to do something else with this click:
var mmClickRecieved = -1;
$("a").click(function(event){
// I am using this as an easy way to mimic your value
if(!(++mmClickRecieved)){
event.preventDefault();
mmNumberOverlay();
}
// You don't need an else, since the event wont be prevented
})
function mmNumberOverlay(){
alert("This happens only once!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Go to Google (this is not allowd in this snippet)!

How to keep the innerhtml content that is changed with the JS onclick function

this is a simple problem but cant seem to solve it.
I want to be able to change the innerhtml content of a link, once is triggered by an onclick function triggered from separate link that actually takes the user to another page (inside the website not external site), I get the script to work but the desirred innerhtml content to be changed dissapears once the page reloads and goes to the other page the link is pointing to. I actually want to keep the change of the text change even if the page is reloaded and taken elsewhere.
The script looks like something like this:
<script>
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
} //Js script that does the innerHMTL change
</script>
eng // button that triggers the onclick function but takes the user to another page inside the site
<a href="http://example.com" id="testchange" >Hello</a> // text to be changed by JS and want to keep the change even if the page is reloaded and taken elsewhere
So any ideas how i could do that? Thanx
For this to work you need some kind of storage. Let's try localStorage:
You first check if the changes has been made before setting the variable, then handle your event:
<script>
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
}
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
//this will save the state of the change
localStorage.setItem('textSet', true);
}
//this will change the text when the page is loaded if the change has been made before.
ready(function(){
if(localStorage.getItem('textSet')){
document.getElementById("testchange").innerHTML = "Get Started";
}
})
</script>
Either use Cookies or Session/Local storage, sessionStorage option below
Data stored in sessionStorage will lasts as long as the browser window is open, whereas localStorage has no expiration time
eng
<a href="http://example.com" id="testchange" >Hello</a>
<script>
function setFlag() {
sessionStorage.setItem('setFlag', 'true');
}
if (sessionStorage.getItem("setFlag"))
document.getElementById("testchange").innerHTML = "Get Started";
</script>
Note: this code will need to be place after your HTML elements ideally at bottom of the page

How do I make the page refresh in Javascript

So I want to make a script like this:
window.location = "http://m.roblox.com/Catalog/VerifyPurchase?assetid=122174821&type=robux&expectedPrice=1"
document.getElementsByClassName('buyButtonClass')[1].click()
but I don't know how to make the page refresh and the code start over without it having to manually be entered again
Thanks
By the way it will be running in Google Chrome Dev. tools Console
I tried
function blah() {
// window.location = "http://m.roblox.com/Catalog/VerifyPurchase?
assetid=122174821&type=robux&expectedPrice=1"
document.getElementsByClassName('buyButtonClass')[1].click()
if (some_condition) {
blah() // rerun the code
}
}
Output was "undefined", the script did nothing.
The script goes to a link, clicks a button (currently it doesn't click for some reason) then restarts the script (not working)
setting window.location = ... will refresh the page, but stuff after that will not trigger, because you just refreshed the page including all the javascript. You can put the code you want to trigger in a $(document).ready(function(){your_code_here}); call and when the page refreshes, it will set up your click event.

auto fill form and submit

I have a form on my 404 page that is auto filled with the address the user tried to find. I also have javascript that then auto submits that form.
The problem is, once it auto submits it keeps looping and the page keeps reloading.
I am trying to wright the javascript code to fire once and then stop.
The script fires on page load so that's whats causing the loop.
Outcome: I need it to fire on page load, page reloads, the code checks to see if its already reloaded once then stops.
For my test I am trying to make it pop an alert that says "I reloaded once" just so I know its worked.
This is my code so far
<script type="text/javascript">
window.onload = function() {
var grabedurl = window.location.href
document.getElementById('badurl').value=grabedurl;
if( history.previous != history.current ){alert('I reloaded once')}
else
setTimeout("document.getElementById('errorsubmit').click()", 3000);}
</script>
What you can do is add the state of the page already having been reloaded or not to the query string part of the URL. This should be done in your form's action, e.g. action="?submitted"
window.onload = function()
{
var form = document.getElementById("aspnetForm");
form.setAttribute("action", form.getAttribute("action") + "&submitted");
var grabedurl = window.location.href;
document.getElementById('badurl').value = grabedurl;
if (/submitted/.test(window.location.search.substring(1)))
{
alert('I reloaded once');
}
else
{
setTimeout("document.getElementById('errorsubmit').click()", 3000);
}
}
However, you might want to consider alternative approaches -- such as submitting the form via an XMLHttpRequest; having another, separate action page to submit the form to, or having the server log the request.

Categories