Run function if window is not active - javascript

I'm currently developing a small conversation system.
When a user writes a new message, the title of the page changes to New Message, which is intended.
However, if the window is active when the message is received, the title should not be updated.
Currently, it will display the New Message regardless of the window is active or not, and only removes it again when a user changes tab and back.
How do I make it only run the if (newCount !== messagesCount) function if the window is not active?
Here's the current code:
if (newCount !== messagesCount) {
document.title = 'New Message - ' + title;
}
$(window).focus(function() {
document.title = title;
});

You can try to track the window status listening to onfocus and onblur windows event, something like:
var hasFocus = true;
window.onfocus = function(){ hasFocus = true;}
window.onblur = function(){ hasFocus = false;}
and check in your method the value of hasFocus

Related

Navigate stop only when going to another website

I am using following code to trigger the are you sure leaving website alert but for some reason its not recognising my if else condition in it and only works if I only put return true in window.onbeforeunload = function() { return true } . Is there a way I can trigger this alert only when user is navigating away from my website cause at the moment without if else condition its asking if user tries to navigate in the same website as well?
window.onbeforeunload = function() {
var location = window.document.activeElement.href;
if (typeof location != 'undefined')
{
console.log(location);
} else { reutn true; }
};
You can set a flag and toggle that flagged based on host of links that are clicked
var host = location.hostname,
allowNavigate = false;
window.onbeforeunload = function() {
if (!allowNavigate) {
return 'Message string';// not what actually gets displayed in most browsers these days
}
//don't return anything
return;
};
window.onload = function() {
document.querySelectorAll('a').forEach(function(a) {
a.addEventListener('click', function(e) {
allowNavigate = this.hostname === host;
});
});
};
The hostname on this page for example is "stackoverflow.com"
DEMO
You can add the "window.onbeforeunload" dynamically for the links you want to see the prompt message
and remove the "window.onbeforeunload" for the links you don't want prompt
<a onClick="a(true)" href="https://www.w3schools.com">Click here to get promt before navigate</a>
<br>
<a onClick="a(false)" href="https://jsfiddle.net/">Click here to navigate without promt </a>
<script>
function a(showPrompt){
window.onbeforeunload = showPrompt ? function(e) {return '';}: null;
}
</script>
https://jsfiddle.net/vqsnmamy/1/

Node.JS & Socket.io - Checking if the tab is selected

For my chat, I want to have notifications. These notifications will act like Gitter's notifications, where it changes the html title to show you have a message. I've googled how to accomplish this, but all answers only worked by checking when the tab is changed. For example,
socket.on('chat message', function (msg) {
// Append the message
appendMessage(msg);
// Check if the window is focused
if (window.onfocus) {
// If it is, there's no need to show there's a new message
document.title = "ChatProject";
}else{
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
});
With the code above, it always shows the notification whether you're on the tab or not. How do I get it to show only when there's a new message?
window.onfocus is an event. Not a state.
By adding a getter and setter to the events you can get the behavior described.
///////////////////////
//Setting OnFocusSate//
///////////////////////
var isFocused = true;
function onFocus(){
isFocused = true;
};
function onBlur() {
isFocused = false;
};
window.onfocus = onFocus;
window.onblur = onBlur;
///////////////////////
//Example Event Check//
///////////////////////
socket.on('chat message', function (msg) {
// Append the message
appendMessage(msg);
// Check if the window is focused
if (isFocused) {
// If it is, there's no need to show there's a new message
document.title = "ChatProject";
}else{
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
});
Cryptic: This works, but when you click back on the tab, the notification doesn't go away. So, we'd have to change the if statement to this
if (!isFocused) {
// If the user is on another tab, show there's a new message
document.title = "[!] ChatProject";
}
Then add this under it
window.onfocus = function() {
document.title = "ChatProject";
}

How to set value of child pop op elements from parent window using Javascript?

I am calling a pop up window from a parent page using :
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
I then try to set the value of two spans which are on chil pop up from parent window using this childWindow object.
childWindow.onload = function () {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
};
this code works fine as long as I am using chrome. But it refuses to work on IE8. There are no console errors either.
I tried removing childWindow.onload = function () { } but then the page would just sort of refresh on both chrome and IE8.
UPDATE
This did not work either.
function CallPopUp(rowindex,controlname ) {
function popupLoad() {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
}
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
if (childWindow.document.readyState === "complete") {
popupLoad();
} else {
childWindow.onload = popupLoad;
}
If test.aspx is in the browser cache, it is possible that the onload event has already happened before you attach your event handler so you're missing it (IE is known to do this with image load events). I'd suggest you check document.readyState before attaching your event handler.
function popupLoad() {
alert('this msg does not shows up when run on IE8');
var hidden1 = childWindow.document.getElementById('hidden1');
var hidden2 = childWindow.document.getElementById('hidden2');
hidden1.innerHTML = rowindex;
hidden2.innerHTML = controlname;
}
var childWindow = open('test1.aspx', '1397127848655', 'resizable=no,width=700,height=500');
if (childWindow.document.readyState === "complete") {
popupLoad();
} else {
childWindow.onload = popupLoad;
}
As another option, you can put the values into the query parameters for the URL:
`"test1.aspx?hidden1=" + rowindex + "&hidden2=" + controlname`
and then have the popup window load it's own fields from it's own onload handler from what's in the query string. Then, you can keep the code in the popup window self contained and you don't have to try to modify one window from another.
If you don't want the user to see this or be able to edit it, you can turn off the location bar in the popup window.

jquery/jscript Prevent open multiple popups

I open a popup with the click event of a hyperlink... The popup contains records from a server.
The problem is that when I click rapidly, there are multiple popups at once.
There is a way to prevent this? in which can open a single popup
My code:
$('.wrapper_form a.add').click(function(e)
{
e.preventDefault();
if(typeof(currentPopup) == 'undefined' || currentPopup.closed)
{
url = 'server_page.aspx';
currentPopup = window.open(url,'server','height=500,width=800');
if (window.focus) {currentPopup.focus()}
}
else
{
currentPopup.focus();
}
});
Here is one approach. Not the best solution but it should work. What this code will do is protect against clicking the link a bunch of times and have it open a new instance for each click. This code will not allow the window to be opened more than once in a 1/2 interval, of course you can change the timing.
var hopefullyThisIsNotInGlobalScope = false;
$('.wrapper_form a.add').click(function(e)
{
if (hopefullyThisIsNotInGlobalScope)
{
return false;
}
hopefullyThisIsNotInGlobalScope = true;
setTimeout(function () { hopefullyThisIsNotInGlobalScope = false; }, 500);
e.preventDefault();
if(typeof(currentPopup) == 'undefined' || currentPopup.closed)
{
url = 'server_page.aspx';
currentPopup = window.open(url,'server','height=500,width=800');
if (window.focus) {currentPopup.focus()}
}
else
{
currentPopup.focus();
}
});
Assuming the popup is on the same domain as the window launching it you might be able to replace hopefullyThisIsNotInGlobalScope variable with a global var attached to the window. You can then set that variable when the popup launches and alter it using the browser unload event

How to verify that the link was clicked using onbeforeunload function in javascript

I am trying to write an integration test using onbeforeunload function, where I click on the image and it launches the url page on the next tab. I need to verify that after the click, new tab was launched. With the script below, it returns false.
if (somename === 'complete') {
var content = document.getElementsByTagName("someframe")[0].contentWindow;
var unloadFlag = false;
window.onbeforeunload = function (e){
unloadFlag = true;
}
var imageClick = content.document.getElementById("imageLayer")
imageClick.click();
assert(unloadFlag === true, "unloadFlag is false");
}

Categories