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

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

Related

Notification with requireInteraction - how to check if displayed?

I show a 'sticky' notification like this:
function show(text) {
let alreadyOn = false; // ??? how to get this ???
if (!alreadyOn) {
new Notification(text, {
requireInteraction : true
});
}
}
Notification.requestPermission();
show("first");
setTimeout(() => show("second"), 1000);
(note this just a sample and you need to permit notification the first time it runs and try again)
Is there a way for my code to later determine if this notification is still on or the user already dismissed it ? That is how to determine alreadyOn above ?
You can add an event handler with Notification.onclose method to do something when the Notification is closed by the user.
Notification.onclose = function () {
// do something...
}

clicking the button in the alert box or overriding the window.alert()?

I have a web application window where I'am required to press a button to remove some stuff many times (the button is easily click-able with JS by selecting it with getElementbyClassName()[i]). But after each click I have to manually press the "OK" button on the window.alert("Are you sure?"); box.
I can't change the websites mechanism as I'm not the owner or developer. But I want somehow to be able to automate this stuff.
JS I use for clicking on the element:
var el = document.getElementsByClassName('ruleAddButton');
for (var i = 0; i < el.length; i++) {
el[i].click();
}
Since alert is only to show info to the user (you can't get user input from an alert), I think you maybe want to monkey patch confirm function this way:
var originalConfirm = window.confirm;
window.confirm = function(msg) {
if (msg.match(/Are you sure/) {
// this confirm should return always true
return true;
} else {
// we want other confirms works as normal
return originalConfirm.bind(window)(msg);
}
}
Just in case, I would do the same trick for alert function
var originalAlert = window.alert;
window.alert = function(msg) {
if (msg.match(/Are you sure/) {
// this is what alert always returns after user clicks OK
return undefined;
} else {
// we want other alerts works as normal
return originalAlert.bind(window)(msg);
}
}
EDIT
Also, you can do something as simple as:
window.confirm = function() { return true; };
But on this case, be aware that ALL confirm calls will be intercepted
You can't click the OK button in a dialog created by window.alert. That dialog is created by the browser and is not controllable from the webpage's JavaScript context. However, what you can do is just monkey-patch the alert function to not show a dialog at all:
window.alert = function() {
// Do nothing.
};
You can override the alert function:
window.alert = function(){}
But it will disable all alerts on this page.

Run function if window is not active

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

Validate context menu item for each tab

I am developing a simple Safari extension that adds a context menu item, which when clicked will let me perform a specific task with the data on the page current. In my injected-scripts.js I have a function validForContextMenu which determines wether or not the context menu should be displayed for the clicked tab. Along with this function I am dispatching the following message to my global.html in order to let it know if the tab should display my context menu item or not.
safari.self.tab.dispatchMessage("validate", validForContextMenu());
In global.html I am doing the following to listen to message, store the data returned by injected-scripts.js, and perform the actual validation:
var contextMenuDisabled = true;
function respondToMessage(theMessageEvent) {
if (theMessageEvent.name === "validate") {
contextMenuDisabled = theMessageEvent.message;
}
}
safari.application.activeBrowserWindow.activeTab.addEventListener("message", respondToMessage, false);
function validateCommand(event) {
event.target.disabled = contextMenuDisabled;
}
safari.application.addEventListener("validate", validateCommand, false);
This all works out quite fine apart from the fact that the validation is only performed once, and only for the tab/page being frontmost at the time my extension loads. If that page is valid for context menu, then so will all other pages and vice versa. I would like the validation to be performed individually for each of Safaris tabs.
Ca this be done? Am I missing something on the way injected scripts or dispatched messages works?
The global.html is singleton and therefore your have only one variable contextMenuDisabled for all tabs. Safari has the special API for this task - safari.self.tab.setContextMenuEventUserInfo.
I use the next code in my extension. In inject.js:
document.addEventListener('contextmenu', onContextMenu, false);
function onContextMenu(ev) {
var UserInfo = {
pageId: pageId
};
var sel = document.getSelection();
if (sel && !sel.isCollapsed)
UserInfo.isSel = true;
safari.self.tab.setContextMenuEventUserInfo(ev, UserInfo);
};
In global.js:
safari.application.addEventListener('validate', onValidate, false);
function onValidate(ev) {
switch (ev.command) {
case 'DownloadSel':
if (!ev.userInfo || !ev.userInfo.isSel)
ev.target.disabled = true;
break;
};
};

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