"Are you sure you want to leave this page?" functions for cancel and OK - onbeforeunload

i'm trying to do something similar to some websites where you leave and it'll display a popup saying "Are you sure you want to leave this page" and with two options saying "Cancel" and "OK".
How would I do that and make it so when you click "Cancel" it'll just cancel the box and when they click "OK" it'll do a 'leaveChat();' function and leave the website?
I've tried using the onbeforeunload which was working but i'm not sure on the function part.
Thanks for the help!

There is no way to do that.
You can try sending the AJAX request in onunload, but I don't think that will work reliably.

To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>

here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}

Related

How to hide popup.html in chrome extension

Here is my setup and i am trying to figure out if its possible.
I have an Chrome Extension which goes and parses some data from a active page and then copys the result to the clipboard. My popup.html is minimal and looks like this
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:600px;">
<textarea id="emailphone" cols="50" rows="10"></textarea>
<br>
<button id="copy-to-clipboard">Copy to Clipboard</button>
</body>
</html>
What i would like to do is actually not even show the popup at all as my script goes and creates an Alert and displays the data. But for one my script sets the Inner Html of the emailphone textarea with the parsed data and then i go and copy the textarea to my clipboard. Here is my popup script
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
emailphone.innerText = request.source;
myFunction();
}
});
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("copy-to-clipboard").addEventListener("click", copytoclipboard);
});
function onWindowLoad() {
var message = document.querySelector('#emailphone');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
emailphone.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function copytoclipboard() {
var copyText = document.getElementById("emailphone");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
alert(copyText.value);
}
window.onload = onWindowLoad;
when i use window.close() it only closes after i close the alert. So what i am looking for is to only show the Alert and not the popup.html

Message box on selected index change

I am trying this JavaScript code to give user a message when selected item from a drop down list contains "Ultra Low" but is not working. Can someone please help?
<script language="javascript" type="text/javascript">
var dropdown = document.getElementById("ddGlass");
dropdown.onchange = function (event) {
if (dropdown.str.indexOf("Ultra Low") > -1) {
alert("Glass Option is for Yuma Only")
}
}
</script>
Where did you get dropdown.str? It should be dropdown.value.

Office 365 outlook appointment addin does not start

We are encountering problems when trying to load our outlook appointment addin. Our command shows up in the ribbon ui and the addin is trying to start and we can trace the calls to our wev-app. We are not getting any errors, 404 or 500 in the tracing and the service responds with our first html-page containing a text and a button to initiate our authentication.
But after the html is returned outlook just stops the spinner for the addin and nothing is showed. Is there any good ways to debug this to understand what is happening?
The html-page is very simple and only contains the code below.
<head>
<title>Office-bokning</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.2.0/fabric.min.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/2.2.0/fabric.components.min.css">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<!--[authentication-popup-script]-->
<script>
startCheck = function () {
var checkCode = setInterval(function () {
localStorage.setItem('dummy', "dummy");
localStorage.removeItem('dummy');
var code = localStorage.getItem('code');
var externalProviderUserId = localStorage.getItem('externalProviderUserId');
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
var fallbackCode;
var fallbackExternalProviderUserId;
if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
fallbackCode = readCookie('NAME_OF_COOKIE');
fallbackExternalProviderUserId = readCookie('externalProviderUserId');
}
console.log("code " + code);
if (code || fallbackCode) {
clearInterval(checkCode);
var http = new XMLHttpRequest();
var url = [URL]
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "text/plain");
//var that = this;
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
localStorage.removeItem('code');
localStorage.removeItem('externalProviderUserId');
window.location.href = "[URL]";
//location.reload();
}
}
http.send(params);
}
}, 1000);
}
startCheck();
</script>
</head>
<body class="container-fluid" style="padding-left: 0px; padding-right: 0px; height: 100%">
<p>
Some text describing the addin...
</p>
<!--[popup-button]-->
<script>
Office.initialize = function (reason) {
console.log("authorize office init" + reason);
var butan = document.getElementById('loginButton');
if (butan)
butan.style.display = 'block';
}
function commandFunction(event) {
event.completed();
}
</script>
</body>
TL;DR : It seems you want to pop up a page for auth. Use the displayDialogAsync API to do that.
Looking at your code, I don't see anything wrong with it. Moreover, the behavior you described is actually correct according to the code you have.
I see that you have a function named "commandFunction" that takes in an "event" parameter. My guess is that you have an ExecuteFunction in your manifest that calls commandFunction.
So when a user clicks on your add-in's button in the ribbon ui of an appointment window, Outlook will load your html webpage, invoke "Office.initialize", show a default spinner for your app just above the "Subject" field of the appointment window, and then call "commandFunction". The only code inside this function is "event.completed", so Outlook calls that code, which basically ends the execution of your app, at which point Outlook removes the default spinner to signal completion. That's exactly what you are experiencing.
You have to run any relevant code inside "commandFunction" before calling "event.completed". So for example, you can add code that will add a notification message/infobar to the appointment before calling "event.completed". Sample code below:
function commandFunction(event)
{
Office.context.mailbox.item.notificationMessages.addAsync
(
"some_unique_id_such_as_a_guid",
{
type: Office.MailboxEnums.ItemNotificationMessageType.InformationalMessage,
persistent: false,
message: "hello world",
icon: "default_icon"
},
function (asyncResult)
{
// check asyncResult.status
// do something
event.completed(true);
}
);
}
It appears that you want to open an html window for the user to authenticate before proceeding with the execution of your app. In that case, you should use the "displayDialogAsync" API by calling it inside "commandFunction" before "event.completed". This will open an IE window that points to authentication page URL. Sample code below:
function commandFunction(event)
{
Office.context.ui.displayDialogAsync
(
"https://ur/to/auth/page",
{
width: 50,
height: 45,
requireHTTPS: true
},
function (asyncResult)
{
// check asyncResult.status
// do something
event.completed(true);
}
);
}
The documentation for the displayDialogAsync API is at: https://github.com/OfficeDev/office-js-docs/blob/master/reference/shared/officeui.md
For debugging, open IE, go to 'Internet Options' -> 'General tab' -> click on 'Settings' button to open the 'Website Data Settings' window. In the 'Temporary Internet Files' tab, under 'Check for newer versions of stored pages', select 'Every time I visit the webpage'. Click Ok.
Now go to 'Advanced' tab -> 'Settings' section and uncheck the following:
Disable script debugging (Internet Explorer)
Disable script debugging (Other)
Then check the following:
Display a notification about every script error
Then add "debugger;" as the first line in "commandFunction":
function commandFunction(event)
{
debugger;
// add other code below...
}
This will prompt you to debug your code when you run the app. And you can debug in Visual Studio and go through your code if you have any other issues.
The HTML you pasted doesn't have a reference to Office.js: <script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>

RealTime Collaborative Text-Editor in Nodejs & Socket.io

I am developing a real-time text editor with paragraph locking property similar to https://quip.com/. in socket.io and nodejs.
It means when you write onto a given paragraph, other collaborators cant edit it.
Moment you hit enter or move cursor to a new line that paragraph becomes Editable for other Collaborators.
I am quite stuck after this. I am thinking a nice approach to move further. Suggestions please.
Below is my code which works perfectly. Till now i can get list of all collaborators and broadcast the content of editor to other collaborators.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Connected Clients</title>
<!--<meta charset="UTF-8"> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="jquery.js"></script> -->
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<textarea id="editor" style="height:200px;width:300px">
Thinknest Pragraph locking Test sample !
</textarea>
<script>
function msgReceived(msg){
//clientCounter.html(msg.clients);
document.getElementById('people').innerHTML=msg.uid;
//console.log(msg.id);
}
var clientCounter;
$(document).ready(function () {
clientCounter = $("#client_count");
var socket = io.connect(
'http://localhost:5000',
{'sync disconnect on unload':true}
);
var uId=prompt("enter your userId",'');
socket.emit('collabrator',uId);
socket.on('message', function(msg){
msgReceived(msg);
});
socket.on('online_collabs',function(data){
$('#online_ppl').html(data);
clientCounter.html(data.length);
});
socket.on('remained_collabs',function(data){
$('#online_ppl').html(data);
clientCounter.html(data.length);
});
socket.on('note_collabs',function(data){
$('#note_colabs').html(data);
});
socket.on('updated_para',function(data){
//$('#editor').append(data);
document.getElementById('editor').innerHTML=data;
});
$('#editor').on('keydown',function(){
//var para=$('#editor').value;
var para= $('#editor').val();
//var para=document.querySelector('[contenteditable]');
// var text=para.textContent;
socket.emit('para',{paragraph:para});
});
});
</script>
<p><span id="client_count">0</span> connected clients</p><br/>
<ul id="people"></ul>
<h3>Online Collaborators</h3>
<span id="online_ppl"></span> <br>
<h3>Note Collaborators</h3>
<span id="note_colabs"></span>
</body>
</html>
server.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(5000);
app.get('/',function(req,res){
res.sendfile("./index.html");
});
var activeClients = 0;
var Collaborators=['Colab1','Colab2','Colab3'];
var people=[];
io.sockets.on('connection', function(socket){
clientConnect(socket);
socket.on('disconnect', function(){
clientDisconnect(socket);
});
socket.on('para',function(data){
//io.sockets.emit('updated_para',data.paragraph);
socket.broadcast.emit('updated_para',data.paragraph);
});
});
function clientConnect(socket){
//activeClients +=1;
var userSocketId=socket.id;
check_Collaborator(socket);
io.sockets.emit('message', {uid:userSocketId});
}
var online_collabs=[];
function check_Collaborator(socket){
socket.on('collabrator',function(data){
if(Collaborators.indexOf(data)!=-1){
socket.data=data;
if(online_collabs.indexOf(data)==-1) {
online_collabs.push(data);
}
io.sockets.emit('online_collabs',online_collabs);
io.sockets.emit('note_collabs',Collaborators);
} else {
console.log("collabrator not found");
}
});
}
function clientDisconnect(socket){
var index=online_collabs.indexOf(socket.data)
if(index>-1)
online_collabs.splice(index,1);
//activeClients -=1;
//io.sockets.emit('message', {clients:activeClients});
io.sockets.emit('remained_collabs',online_collabs);
}
I saw this yesterday already. What exactly is your question? Do you want to know how to 'lock' a text area with javascript? I am confused as to why you put such a strong emphasis on node/socket.io in your question.
Also, next time please format your code. You want help, I get it, but then make it easier for others to help you.
What you have to do in order to make a paragraph not editable by others, I don't know. But let me suggest what I'ld do in socket.io:
Store each paragraph separately and remember who has a lock on it. For locking, I would use the sessionID in case users don't have to register. This would look something like this:
var paragraphs = {
data : [
{
text: "this is an unlocked paragraph",
lock: ""
},
{
text: "this is a locked paragraph",
lock: "oWEALlLx5E-VejicAAAC"
}
]
}
Now, users will likely be allowed to add a paragraph before an existing one. Therefore you should keep an additional index like:
var paragraphs = {
index : [
1,
0
],
data : [
{
text: "this the second paragraph",
lock: "oWEALlLx5E-VejicAAAC"
},
{
text: "this is the first paragraph",
lock: ""
}
]
}
The amount of data being sent over the sockets should now be very small - altough with additional client/server-side logic.
Paragraph lock can be easily achieved by adding a class to the currently editing paragraph. Transfer this paragraph with the class to the other user. so that if the user tries to write over that prevent him by validate with the class.
Generate a class name look like - className_userid (className_1).

Prevent onbeforeunload from being called when clicking on mailto link

Is there anyway to prevent onbeforeunload from being called when clicking on mailto link in chrome.
In FF, Safari, IE it is working fine.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(document).ready(function(){
window.onbeforeunload = confirmExit;
});
function confirmExit() {
return "Are you sure?";
}
</script>
</head>
<body>
Mail Link
</body>
</html>
What about a workaround?
$(document).ready(function(){
mailtoClicked = false;
window.onbeforeunload = confirmExit;
//Test if browser is Chrome
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
$('a[href^=mailto]').click(function() {mailtoClicked = true;});
}
});
function confirmExit() {
if (!mailtoClicked) {
return "Are you sure?";
} else {
mailtoClicked = false;
}
}
Demo.
Here is a proposed solutions that looks reasonable
http://www.ilovebonnie.net/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
UPDATE (link is dead) - Copied contents from Google Cache
How to Use onbeforeunload with Form Submit Buttons
September 23rd, 2009 — Geekery
While doing some programming I came across an interesting predicament. While I understand it’s evil to make it hard for a user to leave a page, I’m not here to argue the merits (or lack thereof) of onbeforeunload.
On a particular form, we are forcing the browser to not cache the information to avoid potential AJAX/JavaScript problems if they should leave the form and come back as browsers don’t all act the same (eg IE leaves checkboxes checked but doesn’t remember changes that have occurred to the page due to JavaScript). As such, we warn our users when they’re about to leave the order form to let them know they’ll need to fill it in again.
The function was simple enough:
window.onbeforeunload = function () {
return "You are about to leave this order form. You will lose any information...";
}
Unfortunately, this would also be triggered if the user submitted the form which, is obviously not what we want. After searching around on the Internet I came across a simple solution that I thought I would share:
// Create a variable that can be set upon form submission
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "You are about to leave this order form. You will lose any information...";
}
}
Since onclick appears to register before onsubmit when clicking a submit button, we can add a little variable declaration to our submit button so that submitFormOkay will be set to true before the form submission happens:
<input type="submit" id="submit_button" onclick="submitFormOkay = true;">

Resources