break a href link event - javascript

I search a method to break the process after click a html a element. It is possible to make a onclick="alert();" event on this a element and the process is temporary stopped, till the OK button is clicked, or the process is breaked, when the page are reloaded or click previous page. Also the break is, but not perfect. With a confirm() it is similare, but by clicking "Cancel" the process is not canceled.
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
}
}
<!DOCTYPE html>
<html>
<body>
example.com
</body>
</html>
The example don't work by me. Here the code:
<!DOCTYPE html>
<html>
<body>
example.com
<script>
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
}
}
</script>
</body>
</html>

I have found a solution, but im not secure is it valide. Pleas help!
There is not so easy why the people think.
The thing is, it should be a solution for existing websites. No new coding is needed. Only insert the function myFunction(). onclick="myFunction()" is always present. And its only possible to put JS code in the head (not in the footer), because for this a custom <script> is always loaded via PHP in the webpages.
First, a methode with only code a new function with javascript:void(0);
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
</body>
</html>
The code:
<!DOCTYPE html>
<html>
<body>
<a id="demo" href="https://www.example.com" onclick="myFunction()" target="_blank" rel="nofollow">example.com</a>
<script>
function myFunction() {
var confirmresult = confirm("Press a button!");
if (confirmresult === true) {
// OK = go away!
} else {
// Cancel = stay here!
document.getElementById("demo").removeAttribute("target");
document.getElementById("demo").href = "javascript:void(0);";
}
}
</script>
</body>
</html>
JSFiddle: https://jsfiddle.net/dLp8qtcm/
Second, a solution with preventDefault(). Consider the event instead a this. For this a edit of the webpages is needed for inside the event in onclick="myFunction(event)".
Thanks for the hints with the preventDefault(), but the examples in the answers don't work by me. Here is a working solution.
The running code snippet function here don't work by me. Below a JSFiddle.
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
example.com
example.com
<script>
function myFunction(e) {
var confirmresult = confirm("Press a button!");
if (confirmresult == true) {
// OK = go away!
} else {
// Cancel = stay here!
e.preventDefault();
}
};
</script>
JSFiddle: https://jsfiddle.net/osanthdq/
EDIT: The matter is a little bit complex. I have explained it here: Event keyword in js

Related

Detect auto-click on a page

I'm trying to develop a library that try to detect auto-click on a page.
The library will be imported on several different pages, some will have jquery, some other will not, or will have other different libraries, so my solution should be vanilla javascript.
the goal is to have several security layers, and the first one will be in javascript, this library will not be the only counter measure against auto-click, but should provide as much informations as possible.
The idea is to intercept all click and touch events that occur on the page, and if those events are script generated, something will happen (should be a ajax call, or setting a value on a form, or setting a cookie or something else, this is not important at this stage).
I've write a very simple script that checks for computer generated clicks:
(function(){
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
try{
document.querySelector('body').addEventListener('click', function(evt) {
console.log("which", evt.which);
console.log("isTrusted", evt.isTrusted);
}, true); // Use Capturing
}catch(e){
console.log("error on addeventlistener",e);
}
}
}
}());
I saw this working on a html page without any other js in it, but since I added this javascript to test the auto-click detection simply "nothing" happens, and with nothing I mean both autoclick and detection.
The same code as follow, if used in the console, is working fine, and events are intercepted and evaulated.
this is the script used:
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
//1 try
el = document.getElementById('target');
if (el.onclick) {
el.onclick();
} else if (el.click) {
el.click();
}
console.log("clicked")
}
//2 try
var d = document.createElement('div'); d.style.position = 'absolute'; d.style.top = '0'; d.style.left = '0'; d.style.width = '200px'; d.style.height = '200px'; d.style.backgroundColor = '#fff'; d.style.border = '1px solid black'; d.onclick = function() {console.log('hello');}; document.body.appendChild(d);
}
the html page is very simple:
<body>
<h1>Hello, world!</h1>
<div id="target"> aaaaa </div>
</body>
and for test purposes I added the detection library in head, while the "autoclick" code is just behind the </body> tag.
I guess the problem is in "how I attach the event handler", or "when", so what I'm asking is what can I do to intercept clicks events "for sure", the idea is to intercept clicks on every element, present and future, I don't want to prevent them, just be sure to intercept them somehow.
Of course I cannot intercept those events that has been prevented and do not bubble, but I'd like to "try" to have my js "before" any other.
Do you have some idea about this?
jsfiddle of example
Using document.onreadystatechange will only work as expected in simple scenerios when no other third party libraries are included. Wrap you code inside the native DOMContentLoaded event.
document.addEventListener("DOMContentLoaded",function(){
document.body.addEventListener('click', function(evt) {
if (evt.target.classList.contains('some-class')) {} // not used
console.log("which", evt.which);
console.log("isTrusted", evt.isTrusted);
}, true);
//this is the autoclick code!
el = document.getElementById('target');
if (el.onclick) {
el.onclick();
} else if (el.click) {
el.click();
}
console.log("clicked")
});
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div id="target"> aaaaa </div>
</body>
</html>
If you look at the event param passed to the function on a click, or whatever other event, you can look for the following which is a telltale sign that the clicker ain't human...
event.originalEvent === undefined
From what you've said I'd use the following to track clicks...
$(document).on("click", function(event){
if(event.originalEvent.isTrusted){
//not human
}else{
//human
}
});
Can you check if both a click event and either a mouseup or touchend event happen within 100 ms of each other? If they don't it's likely an automated event.
let mouseuportouchend = false;
let click = false;
let timer = null;
const regMouseupOrTouchend = function(){
mouseuportouchend = true;
if (!timer) timer = setTimer();
}
const regClick = function(){
click = true;
if (!timer) timer = setTimer();
}
const setTimer = function(){
timer = setTimeout(()=>{
if (click && mouseuportouchend) console.log("Manual");
else console.log ("Auto");
click=false;
mouseuportouchend=false;
timer=null;
}, 100)
}
let el = document.getElementById('target');
el.addEventListener("click",regClick);
el.addEventListener("mouseup", regMouseupOrTouchend);
el.addEventListener("touchend", regMouseupOrTouchend);

How to run js script on button click

How to run this script with button click?
I don't know how to write code for a button and connect it with the code below.
<div id="rez" style="display: none;">BRAVO!</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("100%") != -1) showElement("rez");
}
</script>
a simple google search will yield answers to this kind of questions: http://www.w3schools.com/jsref/event_onclick.asp

Autosave using javascript issue

The following piece of code autosaves a page but it also times it out by loging out and taking the user to a time out page. How can i chnage it so that it only does the auto save part but not the time out?
<script language='javascript'>
function Save() {
var hdnSessionTimeOut = document.getElementById('fast22_MainCtn_fast44');
hdnSessionTimeOut.value = 'SessionTimeOut';
__doPostBack('Fast22$MainCtn$btnSave', '');
}
function Redirect() {
window.location = "SessionTimeout.aspx"
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 30000);
else setTimeout(Redirect, 30000);
}
</script>
I tried reducing it to the following but and I think it worked but it changed the doc to view mode instead of edit mode. and you have to click edit again. Also when it in edit mode, the counter still works and it gives and error. Is there a way to have it auto save and then go back again to edit mode?
<script language='javascript'>
function Save() {
__doPostBack('ctl00$MainContentPlaceHolder$btnSave', '');
}
window.onload = function () {
if ('True' == 'True') setTimeout(Save, 10000);
else setTimeout(Save, 25000);
}
</script>

How to give option to recall function using javascript after running on load

I want to automatically run a function upon loading the webpage, and then I want to give the option to rerun the function after it's executed.
The following code will work if I the part is not in the database, and will work if instead of using document.write is use alert for displaying the part, but if I use document.write, the button to search again disappears. I think it's because the buttons aren't being re-initialized. I've moved that around and gotten nothing, and tried reloading the webpage, which is functional, but unsatisfactory because of the time it takes.
Is there anyway to prevent the buttons from disappearing, or a better method you recommend?
Thanks in advance.
<!DOCTYPE HTML>
<html>
<body>
<input id="clickMe" type="button" value="Search for Another Part" onclick="search_part();" />
<script type="text/javascript">
function search_part()
{
var part = prompt("Stackoverflow example: ");
if( typeof part === 'undefined' )
{
alert("That part is not in the database.")
}
else
{
document.write( part )
}
}
window.onload = search_part();
document.getElementById("Button").onclick = search_part;
</script>
After DOM is loaded, document.write replaces all content on page. Instead you probably want to have a element container on body and display messages in that.
<input id="clickMe" type="button" value="Search for Another Part">
<div id="messages-here"></div>
<script type="text/javascript">
function search_part () {
var part = prompt("Stackoverflow example: ");
if (typeof part === 'undefined') {
alert("That part is not in the database.");
} else {
document.getElementById('messages-here').innerHTML = part;
}
}
window.onload = search_part();
document.getElementById("clickMe").onclick = search_part;
</script>

Javascript not executing when right clicked into new tab

Here is my simple code
function goto() {
/* Some code to be executed */
if (a == "1")
location.href = "http://www.google.com";
else
location.href = "http://www.example.com";
}
And here is html
Hello
this works perfectly fine when i click normally but if i right click it and open in a new tab it doesn't execute.
try this:
Hello
function goto() {
/* Some code to be executed */
window.open("http://www.google.com");
}
if you want to open in new tab on mouse right click,
Hello
hit mouse right click and open in new tab
OR
u can try this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function goto() {
window.location = "http://www.google.com";
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementsByTagName('a')[0].addEventListener('contextmenu', function (ev) {
ev.stopPropagation();
ev.preventDefault();
goto();
});
document.getElementsByTagName('a')[0].addEventListener('click', function (ev) {
goto();
});
}, false)
</script>
</head>
<body>
Hello
</body>
</html>
Try something like this:
Hello
<script>
document.getElementById('myId').addEventListener('contextmenu', function(ev){
gotoFunc(ev);
});
function gotoFunc(ev){
//run this when right clicked over #myId element
}
</script>
do it like this:
function changeDest(elem) {
/* Some code to be executed */
if (a == "1")
elem.href = "http://www.google.com";
else
elem.href = "http://www.example.com";
}
Hello
you can instead use Hello
This should do the trick. i.e adding the url to the href of the anchor tag

Categories