Script that runs in background gets stopped when theres a popUp - javascript

I have this javascript method that needs to run in the background
window.setInterval(function(){
validateCaseStatus();
}, 3000);
On the same page I have a button that asks the user if he wants to submit uploaded documents. But I noticed when the popUp msg(alert) is up the script on the page wont run.
Is there a way to keep the script running?
I use this method to check if the case status is changed and disable window.onbeforeunload.
My question is if theres a way I can keep the script above running even when a popUp alert is shown.
//cancels onbefore close popup when docs are submitted
function validateCaseStatus(){
caseStatus = sforce.apex.execute("IFAP_WebService","CheckCaseStatus", {!$caseId});
if (caseStatus == "Uploaded" || caseStatus == "Submitted")
{
submitted = true;
window.onbeforeunload = null;
validateCaseStatus = null;
}
}

Try using WebWorkers. It's a new html5 concept, and requires a bit more work, but they are very easy to understand and very helpful. See https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers?redirectlocale=en-US&redirectslug=Using_web_workers http://ejohn.org/blog/web-workers/ and http://www.html5rocks.com/en/tutorials/workers/basics/

Related

How can I automatically login to this website?

I'm hoping to use javascript within tampermonkey to scrape https://www.intellizoom.com/ so I can be alerted immediately when any new jobs come in for me to accept (jobs can disappear within seconds if not acted on immediately). Unfortunately my login eventually expires, and the website redirects to https://www.intellizoom.com/login.
I therefore want to use a tampermonkey script matching the login URL to automatically log back in when needed.
I'm struggling to get this to work. First of, it seems you have to focus any input fields before they correctly accept any input from javascript. That works for adding the username and password, but just using focus() on the login button fails.
My test script successfully logs in if, before the message "click!" appears in the console, I physically click anywhere in the website page. (Hence the 5 second setTimeout to give me time to physically click - for test purposes). The login button then turns blue, and the .click(); javascript function then successfully submits the login details.
But, I can't find any way to simulate the physical click using javascript, all attempts to use click() on elements or on co-ordinates just does nothing (with no error messages in the console). Adding focus() before click() doesn't help either.
Can anyone figure out how to submit the login details for this website via javascript?
setTimeout(function(){
document.getElementById("email").focus();
document.getElementById("email").value = "username#Domain.co.uk";
document.getElementById("password").focus();
document.getElementById("password").value = "password";
},500);
setTimeout(function(){
console.log("click!");
document.getElementsByClassName("button large primary is-rounded")[0].click();
},3000);
UPDATE: The solution was kindly provided by Markfila - this code works:
setTimeout(function(){
document.getElementById("email").value = "username#Domain.co.uk";
document.getElementById("password").value = "password";
let event = new Event("blur");
document.getElementById("email").dispatchEvent(event);
document.getElementById("password").dispatchEvent(event);
document.getElementsByClassName("button large primary is-rounded")[0].click();
},100);
I've raised a follow up here question (since I'm not supposed to ask follow questions directly in here).
I dont think you need the focus, there using some kind of third party library for the ui and its not triggering the event that sets the value attribute. After a bit of messing around it looks like the ui library is setting the value on the blur event.
If you add this after setting the value then the login button should enable and the click code you have should work
let event = new Event("blur");
document.getElementById("email").dispatchEvent(event);
document.getElementById("password").dispatchEvent(event);
It seems like the window isn't focused because if you click the window then it will login and clicking the window focuses it.
You could try using var win = window.open("https://www.intellizoom.com/login") then win.focus() to focus the window.
So the whole code would look like this:
var win = window.open("https://www.intellizoom.com/login");
win.focus();
setTimeout(function(){
document.getElementById("email").focus();
document.getElementById("email").value = "username#Domain.co.uk";
document.getElementById("password").focus();
document.getElementById("password").value = "password";
},500);
setTimeout(function(){
console.log("click!");
document.getElementsByClassName("button large primary is-rounded")[0].click();
},3000);
I am not 100% sure about this but by reading your post this is what it made me think.
I hope this helps!

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

Gmail-style Exit Message

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit

Detect Browser Refresh in Javascript

I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.
This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.
$.address.init(function(event) {
}).change(function(event) {
SummaryDiv.SwapPanels(newPanelID);
}
Any ideas?
Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.
checkRefresh: function() {
if (document.location.hash === '#visited') {
console.log('Refreshed');
return true;
} else {
document.location.hash = 'visited';
return false;
}
}
UPDATE
I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.
A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.
Found this on the web for you...
Has both a javascript clever method along with a cookies method.
http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?
I was able to force the change event code to run on refresh by
window.onload = $.address.update(function(){
...
})
In javascript you can do this:
page1.html
<script>
localStorage.removeItem('setear1')
</script>
page2.html
<script>
addEventListener('DOMContentLoaded', () => {
let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
if (vengoDeLaPaginaAnterior === null) {
localStorage.setItem('setear1', 1)
} else {
document.location.href = 'page1.html'
}
})
</script>
then: if user refresh page, return to previus page.

How to block users from closing a window in Javascript?

Is it possible to block users from closing the window using the exit button [X]? I am actually providing a close button in the page for the users to close the window.Basically what I'm trying to do is to force the users to fill the form and submit it. I don't want them to close the window till they have submitted it.
I really appreciate your comments, I'm not thinking of hosting on any commercial website. Its an internal thing, we are actually getting all the staff to participate in this survey we have designed....
I know its not the right way but I was wondering if there was a solution to the problem we have got here...
Take a look at onBeforeUnload.
It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. Are you sure?";
}
</script>
Edit: Most browsers no longer allow a custom message for onbeforeunload.
See this bug report from the 18th of February, 2016.
onbeforeunload dialogs are used for two things on the Modern Web:
Preventing users from inadvertently losing data.
Scamming users.
In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.
Firefox already does this[...]
If you don't want to display popup for all event you can add conditions like
window.onbeforeunload = confirmExit;
function confirmExit() {
if (isAnyTaskInProgress) {
return "Some task is in progress. Are you sure, you want to close?";
}
}
This works fine for me
What will you do when a user hits ALT + F4 or closes it from Task Manager
Why don't you keep track if they did not complete it in a cookie or the DB and when they visit next time just bring the same screen back...:BTW..you haven't finished filling this form out..."
Of course if you were around before the dotcom bust you would remember porn storms, where if you closed 1 window 15 others would open..so yes there is code that will detect a window closing but if you hit ALT + F4 twice it will close the child and the parent (if it was a popup)
This will pop a dialog asking the user if he really wants to close or stay, with a message.
var message = "You have not filled out the form.";
window.onbeforeunload = function(event) {
var e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
};
You can then unset it before the form gets submitted or something else with
window.onbeforeunload = null;
Keep in mind that this is extremely annoying. If you are trying to force your users to fill out a form that they don't want to fill out, then you will fail: they will find a way to close the window and never come back to your mean website.
How about that?
function internalHandler(e) {
e.preventDefault(); // required in some browsers
e.returnValue = ""; // required in some browsers
return "Custom message to show to the user"; // only works in old browsers
}
if (window.addEventListener) {
window.addEventListener('beforeunload', internalHandler, true);
} else if (window.attachEvent) {
window.attachEvent('onbeforeunload', internalHandler);
}
If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.
It's poor practice to force the user to do something they don't necessarily want to do. You can't ever really prevent them from closing the browser.
You can achieve a similar effect, though, by making a div on your current web page to layer over top the rest of your controls so your form is the only thing accessible.
Well you can use the window.onclose event and return false in the event handler.
function closedWin() {
confirm("close ?");
return false; /* which will not allow to close the window */
}
if(window.addEventListener) {
window.addEventListener("close", closedWin, false);
}
window.onclose = closedWin;
Code was taken from this site.
In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.

Categories