How do I make the page refresh in Javascript - 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.

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");
}

Why is my page not rendering the data I need when trying to page redirect in jQuery/JS?

The id's #switchtopagetwo and #switchtoindex are assigned to buttons that do what you can infer from the id's names. What I want to do is on click of the button, I want to redirect to the new page via window.location = url; and then run a function that renders some data on the page via pagetwoData() or pageoneData(), depending on where I am at the moment.
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
pagetwoData();
});
//pagetwo.html button
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
pageoneData();
});
When I comment out window.location, the functions run and I can see the data on the screen, but there's no page redirect even on clicking the button. When I click on the buttons fast enough, I can see the function's data being rendered for a split second and then disappearing. When I console.log certain items, I can see the console.log's appearing in the console and then disappearing the same way.
Clearly there is an issue with window.location. Is there better code I can use for clicking the button, redirecting the page to load the page-2 data, then clicking the button again to go back to page-1 data?
When you redirect to a new page, the entire page context is abandoned and replaced by the new page. Nothing which happens on the source page after that redirect can be relied upon to still happen. But anything on the target page that's loading will happen.
Instead of trying to get Page1 to tell Page2 to do something when it loads, just have that something happen on Page2. For example:
// on index.html
pageoneData();
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
});
// on pagetwo.html
pagetwoData();
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
});
Basically, for any given page, whatever you want to happen on that page when it loads should be executed on that page when it loads.

location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

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 to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}​
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation

Categories