Bind an event with onbeforeunload - javascript

I use the following code to prompt a message if the user close the page :
window.onbeforeunload = function(e) {
e = e ? e : window.event;
if(e) {
e.returnValue = '';
}
return '';
}
I would like to avoid the prompt this message shows when a user clicks a special link (let say id="myid") on the page. Is it possible? I tried like this:
var source = e.target || e.srcElement;
console.log(source);
But source is null, is it possible to bind the event and to check it with onbeforeunload?
and what are the "e" attributes ? how I can look into this "object" ? Any idea ?

Unbind the event if the link is clicked and then redirect
window.onbeforeunload = null;

Related

AddEventListener on every links and childs

Is it possible to attach a new event to every links of a page recursively? Currently I'm using the following code:
var linkHandler = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
console.log("Element clicked, type: "+element.tagName);
if (element.tagName == 'A') {
console.log("Catched "+element.href);
element.href = url(element.href);
}
};
document.addEventListener("click", linkHandler, true);
But it only works if I directly click on a link. For example here, only the click on "Work" of the second link works.
<strong>Doesn't work</strong>
Work <strong>Doesn't</strong>`
Is there another possibility ?

override existing onkeydown function

My extensions go through every input entered on an on any website that is loaded.
What I do is I consider every onkeydown and manipulate it if it has some value.
my background js file contains the following:
document.onkeydown = returnKey;
function returnKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ( node.value == 'fi' ) { evt.srcElement.value = "??"; }
}
My problem is when I have websites that already contains onkeydown function in their innerHTML webpage.
for instance:
taken from facebook's homepage:
<textarea class="uiTextareaAutogrow input" onkeydown="Bootloader.loadComponents(["control-textarea"], function() { TextAreaControl.getInstance(this) }.bind(this));
the switching of node.value == 'fi' in ?? is not executing since their onkeydown="Bootloader...runs before my document.onkeydown.
How do I cause my function to run before their onkeydown is executed?
Instead of document.onkeydown = returnKey;, use
document.addEventListener('keydown', returnKey, true);
The most important part of this line is the third argument. When the value of this parameter is true, the event listener is triggered at capturing phase, which cannot be prevented using event.preventDefault(); or event.stopPropagation();.

Remove onbeforeunload from JS execution in main window from frame

I tried to disable onbeforeunload event from frame script with this command:
window.parent.onbeforeunload = null;
but received this dialog:
I tried to debug and onbeforeunload becomes null. But how I can do so this dialog not shown?
For additional information, I need to trigger this event with JS. At start of the page I set:
window.parent.onbeforeunload = confirm;
where confirm is my own function. But in some places of code I need to disable this event and after that enable with the same command.
This could be happening because null is basically an object in Javascript. Here is how I had written it:
var confirmCloseFn = function(evt) {
if (!captureClose) return;
var message = getLogoffMsg();
evt = (evt) ? evt : window.event;
if(message) {
if (evt) evt.returnValue = message;
return message;
}
else {
if (evt) evt.returnValue = null;
return null;
}
};

How to implement jQuery's .not()?

I have code like:
document.onmousedown = function(){
alert('test');
}
Now, except the element with ID "box", clicking should call this function, i.e. the equivalent of jQuery's .not() selector.
The jQuery code would be:
$(document).not('#box').mousedown(function(){
alert('test');
});
How can I achieve the same thing without using jQuery?
Edit: I don't want jQuery code, but i want an action similar to the .not() selector of jQuery in Javascript.
Edit: I am making an addthis-like widget. It is a 10kb file which will show a popup when a text is selected. It will not use jQuery.
In my case, when a text is selected, a popup is shown. When the document is clicked somewhere other than the widget, the widget should disappear.
To do this properly, you need to check whether e.target || e.srcElement or any of its parents has id === 'box'.
For example: (with jQuery)
$(document).mousedown(function(e) {
if ($(e.target).closest('#box').length)
return;
//Do things
});
Without jQuery:
function isBox(elem) {
return elem != null && (elem.id === 'box' || isBox(elem.parentNode));
}
document.onmousedown = function(e) {
e = e || window.event;
if (isBox(e.target || e.srcElement))
return;
//Do things
};
Alternatively, you could handle the mousedown event for the box element and cancel bubbling.
Here's one way that should work:
document.onmousedown = function(e){
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== "box") { alert("hi"); }
}
or if you would like it to be reusable with different ids:
function myNot(id, callback) {
return function (e) {
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== id) { callback(); }
}
}
and to use it:
document.onmousedown = myNot("box", function () {
alert("hi");
});
The cleanest way I can come up with for what you're trying to do is to set a document.onmousedown event and then halt event propagation on the box.onmousedown event. This avoids creating a large number of onmousedown events all over the document, and avoids having to recurse through the entire parent hierarchy of a node every time an event is triggered.
document.onmousedown = function() {
alert("Foo!");
};
document.getElementById("box").onmousedown = function(e) {
alert("Bar!");
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
};

how to check when field enter/return has been pressed on?

I have multiple fields, typically enter will be pressed on one of the two main ones. I want to know which field enter has been pressed on, how do i do this? (i dont know much JS)
its simple to add an "onkeypress" event to each of the fields, and then in the event handler to examine the keycode that is attached to the event. For example, consider the following code:
form.elements['fieldone'].onkeypress = function(evt) {
if (window.event) evt = window.event; // support IE
if (evt.keyCode == 13) alert("Enter was pressed!");
return true;
}
Please note that under most browsers, pressing ENTER in a form field would post that form. If you don't want that to happen, you can simply return false from the onkeypress handler and that would tell the browser to ignore that key.
Check for enter and set some hidden field (example uses JQuery):
$('#input_text').keyup(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
alert('Enter key was pressed.');
}
});
Include this in your page, it should fire automatically when you hit any key and tell you which html element had focus when it happened.
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event;
f ((e.charCode) && (e.keyCode == 13))
alert('Yay! Enter was pressed while field ' + document.activeElement.id + ' had focus!');
}
</script>
You can check from which element the event bubbled from using something like the following
var text1 = document.getElementById('text1');
var text2 = document.getElementById('text2');
text1.onkeypress = keyPresser;
text2.onkeypress = keyPresser;
function keyPresser(e) {
// to support IE event model
var e = e || window.event;
var originalElement = e.srcElement || e.originalTarget;
if (e.keyCode === 13) {
alert(originalElement.id);
}
}
Here's a Working Demo
I would recommend taking a look at the differences in Browser event models and also at unobtrusive JavaScript .
QuirksMode - Introduction to Events
The IE Event Model
Pro JavaScript Techniques - Unobtrusive Event Binding
Use event delegation to avoid attaching event handlers to a large number of elements:
window.onload = function () {
document.onkeyup = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
keyCode = e.keyCode || e.which;
if (target.tagName.toLowerCase() == 'input' && keyCode == 13) {
alert('Enter pressed on ' + target.id);
}
};
};

Categories