Applied onbeforeunload in body tag to logout user when a tab/browser is closed in an MVC Application.
I somehow managed to bypass redirecting to other links and also F5, but when I click on refresh button it logs me out, also when I select url in address bar and hit enter it logs me out.
<body onbeforeunload="UserLogoutOnBrowserClose(event)">
<script>
var href;
var id;
var logout;
var descargar;
var isF5Pressed;
$('a').click(function () {
href = ($(this).attr('href'));
id = ($(this).attr('id'));
if (id === "logout")
logout = id;
else if (id === "descargar")
descargar = id;
});
$(document.body).on("keydown", this, function (event) {
if (event.keyCode == 116) {
isF5Pressed = true;
}
});
$(window).on("unload", this, function (event) {
console.log(window.performance);
});
function UserLogoutOnBrowserClose(e) {
debugger;
var navigation = e.currentTarget.performance.navigation.type;
var activeElement = document.activeElement;
var myWindow;
var Uri = '#Url.Action("LogOff", "Account",new { area="" })';
var bodyID = '#bodyId';
var attributes = document.activeElement.attributes;
var attributesId = (document.activeElement.attributes).id;
var baseURI = document.baseURI;
// submit-pse-button check is applied to prevent user from signing out while redirecting to PSE portal
if (attributesId.value === "submit-pse-button" || attributesId.value === "reclamarButton" || activeElement.localName === "a"
|| activeElement.localName === "button" || logout != undefined || descargar != undefined || isF5Pressed != undefined) { }
else {
if (attributes.href != undefined) {
if (bodyID === "customer" && baseURI == attributes.href.value)
myWindow = window.open(Uri, "");
}
else {
if (bodyID === "customer")
myWindow = window.open(Uri, "");
}
}
}
</script>
How to bypass all other events like form submits, anchor tag clicking, button pressing input submits to have this event fired or at least can check if any of the above is clicked/hit/submitted.
Related
This is my script
<script>
var InputContainer = document.getElementsByClassName("InputContainer")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}
</script>
I have also put a around the entire form.
You can find the original webpage at: https://im-here.biz/ContactForm/contact-inc.php
Obviously, I am doing something wrong here.
Ideas?
I can see an error in the console on the above-mentioned URL. By seeing your code there is no container defined. I guess you should be using InputContainer instead of the container variable or change the declaration like this:
<script defer>
// Put your code here
var container = document.getElementsByClassName("InputContainer")[0];
</script>
So I have a project, which needs to have a sample login page, using this it was working but now it is not opening the url in the If statement
function validate() {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
}
You can solve this by adding to the button on your form the attribute: type="button"
<button type="button" onclick="validate()">Login</button>
and your code will work perfectly, but notice that you need to consider the form being submitted also (by pressing Enter button on keyboard). Maybe try changing your code to this:
<script>
$('#form').on('submit', function(e) {
var usern = document.getElementById("userIn").value;
var passw = document.getElementById("passIn").value;
var position = -1;
var usernArray = ["User1", "User2"];
var passwArray = ["Pass1", "Pass2"];
for (var i=0; i <usernArray.length; i++) {
if ((usern == usernArray[i]) && (passw == passwArray[i])) {
position = i;
break;
}
}
if (position != -1)
{
alert("Login Was Successful!, You are being redirected to the homepage");
window.location.href = 'home.html';
}
else
{
alert("Invalid Username and/or Password! Please try again.")
}
e.preventDefault();
return false;
});
</script>
and set the type attribute to your button to submit
Could you try this window.location.href=/home.html so it is relative to the current domain. Or you could try the window.location.replace instead of href.
I have a script that tracks outgoing links when the link is inside an <a> tag.
The script is from here
The script will track html inside the tag or an image.
What I need is for it to track a button as seen below.
Here is the code I guess I need to modify:
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
Here is the button I want to track
<button type="button" title="title" style="background:#cda85c;" class="button btn-cart" onclick="window.open('http://www.example.com')"><span><span><?php echo $this->__('Buy Now') ?></span></span></button>
Here is the full script:
function clicktracker_inarray (arr, val)
{
for (var i in arr) if (arr[i] == val) return true;
return false;
}
// ***** clicktracker_innertxt *****
function clicktracker_innertxt(str)
{
str = str.replace(/<[^>]*>/g, ' ');
str = str.replace( /&/g, '&');
str = str.replace( / /g, ' ');
str = str.replace( /^\s+/g, '');
str = str.replace( /\s+$/g, '');
return str;
}
// ***** URL *******************************************************************
var clicktracker_re_scheme = "^\\w+://";
var clicktracker_re_folder = "((?:-|\\w|\\.)*)";
var clicktracker_re_domain = clicktracker_re_scheme+ clicktracker_re_folder;
var clicktracker_re_urlall = clicktracker_re_domain+"(?:/"+clicktracker_re_folder+')*';
// ***** clicktracker_domain *****
function clicktracker_domain(url)
{
var reg = new RegExp(clicktracker_re_domain);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1];
return match;
}
// ***** clicktracker_extension *****
function clicktracker_extension(url)
{
var reg = new RegExp(clicktracker_re_urlall);
var match = reg.exec(url);
if (!match) return "";
match = match[match.length-1].split(".");
return (match.length >= 2) ? match[match.length-1] : "";
}
// ***** Track *****************************************************************
// ***** clicktracker_aux *****
function clicktracker_aux(url, title)
{
var img = new Image();
img.src = clicktracker_url+"?url="+url+"&title="+title+"&rand="+Math.random();
}
// ***** clicktracker *****
function clicktracker(e)
{
var ie = navigator.appName == "Microsoft Internet Explorer";
var src = ie ? window.event.srcElement : e.target;
var tag = (src.tagName.toLowerCase() != "a") ? src.parentNode : src;
if (!tag || tag.tagName.toLowerCase() != "a") return;
domain = clicktracker_domain (tag.href);
extension = clicktracker_extension(tag.href);
if ( clicktracker_inarray(clicktracker_domains, domain) &&
!clicktracker_inarray(clicktracker_extensions, extension)) return;
var url = tag.href;
var title = '';
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.innerHTML);
if (!title) if (tag.tagName.toLowerCase() == "a") title = clicktracker_innertxt(tag.title);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt(src.alt);
if (!title) if (src.tagName.toLowerCase() == "img") title = clicktracker_innertxt("Image");
url = escape(url .substr(0, 150));
title = escape(title.substr(0, 150));
if (url && title) setTimeout("clicktracker_aux('"+url+"', '"+title+"')", 10);
return;
}
// ***** Attach Events *********************************************************
if (navigator.appName == "Microsoft Internet Explorer")
document.attachEvent ('onclick', clicktracker);
else document.addEventListener('click', clicktracker, false);
edit*****
The clicks are then stored in the database and called for from a php page.
There's a lot going on in those scripts and it's not clear what you mean by "track", so I'll just give a short version:
document.addEventListener('click',function(e){
var tag=e.target.tagName.toLowerCase();
switch(tag){
case "a":
//use e.target to track this link event
break;
case "img":
//use e.target to track this image event
break;
case "button":
//use e.target to track this button event
break;
}
});
This listens for clicks anywhere on the page, and you use e.target to inspect the click.
Edit:
e is just the name I gave to the event object, which is automatically passed into the function by the event listener. One of the properties that's always in this object is target which contains a bunch of info about the event. if you drop console.log(e) inside the function in the event listener above, you can pull it up in Chrome, hit control+shift+i, go to the javascript console, and explore what's in there.
I call
element.focus();
Where element is HTMLInputElement of type=button.
But then the browser clicks the button! That's in mozilla and chrome.
How do i highlight the button with selection, but not initiate the click event?
No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit
It does exactly what you want it to.
Well, i've identified the reason.
I was handling the onkeydown event for Enter key.
The solution is to use
e.preventDefault();
function ConvertEnterToTab(s, e, numSkipElements) {
var keyCode = e.keyCode || e.htmlEvent.keyCode;
if (keyCode === 13) {
var tabIndex = s.tabIndex || s.inputElement.tabIndex;
if (numSkipElements == undefined) {
numSkipElements = 0;
}
var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
if (nextElement != undefined) {
nextElement.focus();
return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
}
}
}
function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
if (maxTabIndex == undefined) {
maxTabIndex = 100;
}
var tempIndex = currentTabIndex + 1;
while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
tempIndex++;
}
return $('[tabindex=' + tempIndex + ']')[0];
}
I need to check onload if an anchor is within the URL to open a tab if required. The problem is that if a user opens a tab before the onload function gets fired, the tab gets closed and the user needs to open it again.
How to fix that?
HTML:
<body onload="checkurl()">
JS:
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout');
}
else if (window.location.hash == '#contact')
{
showhide('seccontact');
}
}
JS function:
var divState = {};
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
}
Thanks.
Uli
I'm pretty sure that <script> tags inside of <head> execute right away before onload() so try that.
You can call the function with an extra parameter to make sure will show in your load function.
Then check on a global initialized variable to check if the function has already been executed by user when running from the checkurl function. This is required if the user clicks on a different tab than the one specified in the URL.
Also you need to check on divState[id] instead of divid.style.display == 'block' when updating divid.style.display at bottom.
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout', true);
}
else if (window.location.hash == '#contact')
{
showhide('seccontact', true);
}
}
var divState = {};
var initialized = false;
function showhide(id, initialize) {
if(initialized && initialize) return;
initialized = true;
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
if(initialize){
divid.style.display = 'block';
} else {
divid.style.display = (divState[id] ? 'block' : 'none');
}
}
}