How to detect search provider which has already been added? - javascript

I'm trying to build a feature like whenever a user comes to my site, I have added an option to add default search provider in their browser. I have written a code like this for Firefox -
<script>
$(document).ready(function () {
var isFirefox = typeof InstallTrigger !== 'undefined';
if (isFirefox === false) {
$("#set-susper-default").remove();
$(".input-group-btn").addClass("align-search-btn");
$("#navbar-search").addClass("align-navsearch-btn");
}
if (window.external && window.external.IsSearchProviderInstalled) {
var isInstalled = window.external.IsSearchProviderInstalled("http://susper.com");
if (!isInstalled) {
$("#set-susper-default").show();
}
}
$("#install-susper").on("click", function () {
window.external.AddSearchProvider("http://susper.com/susper.xml");
});
$("#cancel-installation").on("click", function () {
$("#set-susper-default").remove();
});
});
</script>
User clicks on the install button and script runs and the site is added in search provider list. If a user refreshes or again comes to my site, this feature again come. How should I detect it is already added so that whenever a user comes to my site next time it does not appear.
It would be great help if someone can help me out. Thanks :)

Unfortunately you can’t use IsSearchProviderInstalled and AddSearchProvider. They are considered no-ops in Chrome, and should do nothing as HTML Standard describes, more info here: https://www.chromestatus.com/feature/5672001305837568. For now AddSearchProvider works in Firefox, but IsSearchProviderInstalled will return always 0. You can try it by going to https://google.com and adding this code: external.IsSearchProviderInstalled("https://www.google.com"); in the console.
Instead you should try adding search plugin autodiscovery into your webpage. To do so just add the <link> element to the <head>:
<link rel="search"
type="application/opensearchdescription+xml"
title="searchTitle"
href="pluginURL">
More info about it here: https://developer.mozilla.org/en-US/Add-ons/Creating_OpenSearch_plugins_for_Firefox#Autodiscovery_of_search_plugins

Related

Getting a href source within the iframe [duplicate]

I got a warning by my ad system provider about click fraud. No further info, all they are recommending is "hide the ads for users who click on ads too quickly'". I wrote a piece of JS script that hides all DIVs with ads for N seconds (using cookie) when clicked on, but this solution does not work as the "inner" content (with ads) is generated by an JS script that calls and renders the content from external server (as you would expect from an ad system). So, when one takes the cross-domain security into account it is kinda Catch 22. How can I detect a click inside a DIV (locally defined) of which content is rendered by an external JS and in iframe?
Example:
<div class="ad-class"> <!-- locally defined div -->
<div id="my-id"> </div> <!-- identifies my ad in the provider's system -->
<script>
var foo = blah // declares the ad dimensions and stuff
// and renders the contextual ad in #my-id DIV
</script>
</div>
Were it all local, solution would be easy as the internal div would inherit the parent class ("ad-class"). In case of cross-domain, this is not valid. Any tips, dudes?
You cannot detect click events in cross-domain iframe.
That put, you might have one bad option:
One of the nearest things you can do is detect that the focus moved from your window to the iframe:
window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
if(document.activeElement == document.querySelector('iframe'))
{
alert('Focus Left Current Window and Moved to Iframe / Possible click!');
}
});
http://jsfiddle.net/wk1yv6q3/
However it's not reliable, loose focus does not mean a click, it could be user moving across the website using TAB.
Another problem is that, you only detect the first time focus is moved to the iframe, you do not know what user does in there, he can click a million times and you will never know.
Luizgrs inspired me this solution :
var clickIframe = window.setInterval(checkFocus, 100);
var i = 0;
function checkFocus() {
if(document.activeElement == document.getElementById("ifr")) {
console.log("clicked "+(i++));
window.focus();
}
}
<!DOCTYPE html>
<h2>Onclick event on iframe</h2>
<iframe src="https://www.brokenbrowser.com/" id="ifr"></iframe>
The function detect if the iframe has the focus, if yes, the user clicked into the iframe. We then give back the focus to our main windows, which allow us to find if the user click another time.
This trick has been usefull to me for a POC on a 2 step iframe click-jacking. Getting to know when the user clicked for the first time on the iframe allowed me to reorganize my different layers to keep the illusion perfect.
The approach #Luizgrs pointed out is very accurate, however I managed to indeed detect the click event using a variation of the method:
var iframeMouseOver = false;
$("YOUR_CONTAINER_ID")
.off("mouseover.iframe").on("mouseover.iframe", function() {
iframeMouseOver = true;
})
.off("mouseout.iframe").on("mouseout.iframe", function() {
iframeMouseOver = false;
});
$(window).off("blur.iframe").on("blur.iframe", function() {
if(iframeMouseOver){
$j("#os_top").click();
}
});
The above code works like a charm on desktop if you want to add mobile support you just need to use touch events touchstartand touchendevents to simulate the mouseover on mobile.
Source
Well, a while ago I found this plugin for WordPress. Obviously it does what I need -- just wondering how this guy made it to work, it does count clicks on Adsense iframe. I must have a closer look though I am not a PHP programmer. I program mainly in Python and need some solution of this kind for Django. If anyone can read the code easily, I would appreciate any help.
The plugin is searching first for any iframe wrapped by a previous specified class name.
The iframe id´s will be collected in a array and for everyone of these id´s an mouseover event will be created which fires the script which hides the class 'cfmonitor'. As a result the iframe containing ad is not visible anymore.
// IFRAME ACTION
function iframeAction () {
jq.each(jq.cfmonitor.iframes, function(index,element) {
frameID = jq(element).attr('id') || false;
if (frameID) initiateIframe(frameID);
//alert (frameID);
});
}
// INIT IFRAME
function initiateIframe(elementID) {
var element = document.getElementById(elementID);
// MOUSE IN && OUT
if (element) {
element.onmouseover = processMouseOver;
element.onmouseout = processMouseOut;
//console.log("mouse on out");
}
// CLICKS
if (typeof window.attachEvent !== 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener !== 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
// IFRAME CLICKS
function processIFrameClick() {
// ADD A CLICK
if(isOverIFrame) {
//addClick();
// Some logic here to hide the class 'cfmonitor'
//console.log("Go");
top.focus();
}
}
Check this it might help. You can not detect the click event when its cross browser.
window.focus();
window.addEventListener('blur', function(e){
if(document.activeElement == document.getElementById('Your iframe id'))
{
console.log('iframe click!');
}
});

Trying to disable the browser's back button

I've written two HTML files:
Login.html
Next Page
Home.html`
<html>
<body>
<a href = >Login.html>>Prev Page</a>
</body>
<script type = "text/javascript" >
history.pushState("anything", "", "#1");
window.onhashchange = function (event) {
window.location.hash = "a";
};
</script>
</html>
`
I'm trying to disable browser's back button. If i execute this code on chrome it doesn't disable the back button but if i run history.state command in console of Home.html page and then i click the back button, then it remains on same page(works as expected). Why so?
FOA, Thanks everyone for your answers.
Finally below code gave me the solution:
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();
You can't disable the browser's back button. If you could, that would be a security hazard and the browser vendors would most likely seek to fix it.
It is generally a bad idea overriding the default behavior of web browser. Client side script does not have the sufficient privilege to do this for security reason.
There are few similar questions asked as well,
How can I prevent the backspace key from navigating back?
How to prevent browser's default history back action for backspace button with JavaScript?
You can-not actually disable browser back button. However you can do magic using your logic to prevent user from navigating back which will create an impression like it is disabled. Here is how, check out the following snippet.
(function (global) {
if(typeof (global) === "undefined") {
throw new Error("window is undefined");
}
var _hash = "!";
var noBackPlease = function () {
global.location.href += "#";
// making sure we have the fruit available for juice (^__^)
global.setTimeout(function () {
global.location.href += "!";
}, 50);
};
global.onhashchange = function () {
if (global.location.hash !== _hash) {
global.location.hash = _hash;
}
};
global.onload = function () {
noBackPlease();
// disables backspace on page except on input fields and textarea..
document.body.onkeydown = function (e) {
var elm = e.target.nodeName.toLowerCase();
if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {
e.preventDefault();
}
// stopping event bubbling up the DOM tree..
e.stopPropagation();
};
}
})(window);
This is in pure JavaScript so it would work in most of the browsers. It would also disable backspace key but key will work normally inside input fields and textarea.
Recommended Setup:
Place this snippet in a separate script and include it on a page where you want this behavior. In current setup it will execute onload event of DOM which is the ideal entry point for this code.
Working Demo link-> http://output.jsbin.com/yaqaho
The HTML5 History API gives developers the ability to modify a website's URL without a full page refresh. This is particularly useful for loading portions of a page with JavaScript, such that the content is significantly different and warrants a new URL.
You can check this link it may helpful
https://css-tricks.com/using-the-html5-history-api/

Button not redirecting to the correct link?

I am having an issue with a button that is bounded to a javascript function with onClick();
My interface can ban pepoles on a game server but for now if i select anyone here : It will always select wartog for some reason.
In my code everything looks to redirect to the correct person.
<script type="text/javascript">
var link="scripts/playerManager/ban.php?player=IIPoliII&serverpath=server/x1&user=Poli";
function editLinkIIPoliII() {
var x = prompt("Reason:", "");
if (x === "" || x === null) {
alert("You entred no reason please retry to ban this player with a reason");
} else {
link+="&reason=" +x;
window.location=link;
}
}
</script>
<a onclick="editLinkIIPoliII()" href="#">Ban</a></td>
Here you can see the link for IIPoliII it looks alright, also if i use the inspection tool it's clicking on the right place.
I cleared my cache and tried also in internet explorer it's the same everywhere sadly ....
Why is it missunderstanding the link?
As Rafael Duarte said it's because my var link don't change at all. It's not dynamic so i will always apply the lastest player

ZeroClipboard user script adding in mouse over, working in firefox, but not chrome

I am using zeroclipboard to add a "copy" link to each row in a fairly large list, within a user script. To accomplish that, I using a method similar to the one listed on this page, where the ZeroClipboard.Client() element for each row is created when the user mouses over the row. This is working great in FireFox, but not in Chrome.
Also as a note: I copied the contents of the ZeroClipboard.js file into the user script itself instead of including it in an external file.
Here is the markup that creates the copy button for each element
<span style="color:blue; text-decoration:underline; cursor:pointer" id="copy_'+id+'" class="CopyLink" link="'+url+'" onmouseover="clipboard.add(this)">Copy</span>
Here is the code segment that adds the clipboard's client object:
function main(){
window.clipboard = {
load: function (){
if(!clipboard.initialized){
ZeroClipboard.setMoviePath("http://www.swfcabin.com/swf-files/1343927328.swf");
clipboard.initialized=true;
console.log("Clipboard intialized");
}
},
add: function(element){
clipboard.load();
var clip = new ZeroClipboard.Client();
console.log('Clipboard client loaded: ' + element.id);
clip.glue(element, element.parentNode);
console.log('Clipboard glued: ' + element.id);
clip.setText(element.getAttribute('link'));
console.log('Clipboard text set: ' + element.getAttribute('link'));
clip.addEventListener('complete',function(client,text) {
console.log('Clipboard copied: ' + text);//doesn't fire in chrome
});
clip.addEventListener('load',function(client) {
console.log('Clipboard loaded: ' + element.getAttribute('link'));
});
}
}
//other code in user script including injecting above markup
//as well as contents of ZeroClipboard.js
window.ZeroClipboard = { ... }
}
var script = document.createElement("script");
script.appendChild(document.createTextNode('('+main+')()'));
(document.head || document.body || document.documentElement).appendChild(script);
In this block, every console.log fires in FireFox when I mouse over and click the copy span, but in chrome, all except the 'complete' listener fire. I was able to verify that ZeroClipboard is working in my Chrome by using the example on this page. I am also able to verify that the flash object is being added to the page in the correct location, but it is simply not responding to a click.
Since the zeroclipboard code is no longer being maintained according to the site, I'm hoping someone out there can help me out. I'm thinking there is possibly some issue with dynamically adding the embedded flash objects in chrome on mouseover, or perhaps some difference between user scripts in chrome vs firefox with greasemonkey? Any help would be greatly appreciated, thanks
I'm not sure the reason behind it but I have been running into this on Chrome as well. I had two zeroclipboard implementations, one that was visible on page load, and one that was only visible when the user opened a dialog. The one that was visible on page load worked as expected, but the other one didn't. In order to "solve" the issue, I had to render the zeroclipboard link, set its absolute position to be off the screen (-500 px), then add some javascript to move the link into place when the dialog opens. This is an ugly solution but I think is the only way to get it to work in Chrome. Your case is particularly hairy since you have lots of dynamic zeroclipboards on your page whereas I only had one, but it seems to me that there's no reason this won't work for you.
<!-- <script type="text/javascript" src="http://davidwalsh.name/demo/ZeroClipboard.js"></script> -->
function copyText(fieldName,buttonName){
var fieldNameTemp =fieldName;
var buttonNameTemp =buttonName;
var val = "";
try{
val = navigator.userAgent.toLowerCase();
}catch(e){}
var swfurl = "js/ZeroClipboard.swf";
setTimeout(function () {
ZeroClipboard.setMoviePath(swfurl);
var clip = new ZeroClipboard.Client();
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById(fieldNameTemp).value);
});
clip.addEventListener('complete', function (client, text) {
try{
if(val.indexOf("opera") > -1 || val.indexOf("msie") > -1 || val.indexOf("safari") > -1 || val.indexOf("chrome") > -1){
alert('Your text has been copied');
}
}catch(e){
alert('Please alert not use on fireFox');
}
});
clip.glue(buttonNameTemp);
}, 2000);
}

How do I disable right click on my web page?

Can I disable right click on my web page without using JavaScript? I ask this because most browsers allow user to disable JavaScript.
If not, how do I use JavaScript to disable right click?
You can do that with JavaScript by adding an event listener for the "contextmenu" event and calling the preventDefault() method:
document.addEventListener('contextmenu', event => event.preventDefault());
That being said: DON'T DO IT.
Why? Because it achieves nothing other than annoying users. Also many browsers have a security option to disallow disabling of the right click (context) menu anyway.
Not sure why you'd want to. If it's out of some misplaced belief that you can protect your source code or images that way, think again: you can't.
DON'T
Just, don't.
No matter what you do, you can't prevent users from having full access to every bit of data on your website. Any Javascript you code can be rendered moot by simply turning off Javascript on the browser (or using a plugin like NoScript). Additionally, there's no way to disable the ability of any user to simply "view source" or "view page info" (or use wget) for your site.
It's not worth the effort. It won't actually work. It will make your site actively hostile to users. They will notice this and stop visiting. There is no benefit to doing this, only wasted effort and lost traffic.
Don't.
Update: It seems this little topic has proven quite controversial over time. Even so, I stand by this answer to this question. Sometimes the correct answer is advice instead of a literal response.
People who stumble on this question in hopes of finding out how to create custom context menus should look elsewhere, such as these questions:
Making custom right-click context menus for my web-app, which relies on jQuery
How to add a custom right-click menu to a webpage, which uses pure javascript/html
The original question was about how to stop right-click given that the user can disable JavaScript: which sounds nefarious and evil (hence the negative responses) - but all duplicates redirect here, even though many of the duplicates are asking for less evil purposes.
Like using the right-click button in HTML5 games, for example. This can be done with the inline code above, or a bit nicer is something like this:
document.addEventListener("contextmenu", function (e){
e.preventDefault();
}, false);
But if you are making a game, then remember that the right-click button fires the contextmenu event - but it also fires the regular mousedown and mouseup events too. So you need to check the event's which property to see if it was the left (which === 1), middle (which === 2), or right (which === 3) mouse button that is firing the event.
Here's an example in jQuery - note that the pressing the right mouse button will fire three events: the mousedown event, the contextmenu event, and the mouseup event.
// With jQuery
$(document).on({
"contextmenu": function (e) {
console.log("ctx menu button:", e.which);
// Stop the context menu
e.preventDefault();
},
"mousedown": function(e) {
console.log("normal mouse down:", e.which);
},
"mouseup": function(e) {
console.log("normal mouse up:", e.which);
}
});
So if you're using the left and right mouse buttons in a game, you'll have to do some conditional logic in the mouse handlers.
If you don't care about alerting the user with a message every time they try to right click, try adding this to your body tag
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).
However, as mentioned in the other answers, there really is no point adding a right click disabler. Anyone with basic browser knowledge can view the source and extract the information they need.
If you are a jquery fan,use this
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
First, you cannot achieve this without using a client side capability. This is where the javascript runs.
Secondly, if you are trying to control what an end user can consume from your site, then you need to rethink how you display that information. An image has a public url that can be fetched via HTTP without the need for a browser.
Authentication can control who has access to what resources.
Embedded watermarking in images can prove that the image was from a specific person/company.
At the end of the day, resource management is really user/guest managment.
The first rule of the Internet, if you dont want it taken, dont make it public!
The second rule of the Internet, if you dont want it taken, dont put it on the Internet!
If your goal is to disallow users to simply save your images, you can also check if the clicked target is an image, only disable right click in that case. So right click can be used for other purposes. Taken from the code above:
document.addEventListener("contextmenu", function(e){
if (e.target.nodeName === "IMG") {
e.preventDefault();
}
}, false);
This is just to take away the easiest way of saving your images, but it can still be done.
If your aim is to prevent people being able to download your images, as most people have said, disabling right click is pretty much ineffective.
Assuming you are trying to protect images the alternative methods are -
Using a flash player, users can't download them as such, but they could easily do a screen capture.
If you want to be more akward, make the image the background of a div, containing a transparent image, à la -
<div style="background-image: url(YourImage.jpg);">
<img src="transparent.gif"/>
</div>
will be enough to deter the casual theft of your images (see below for a sample), but as with all these techniques, is trivial to defeat with a basic understanding of html.
You cannot accomplish what you're asking without using Javascript. Any other technology you may choose to use can only help to compose the web page on the server side to be sent to the browser.
There simply is no good solution, and there is no solution period without Javascript.
If you just want to disable right click for saving images on the web page, go with this CSS solution:
your-img-tag {
pointer-events: none;
}
Before Implemented On Same Image:
After Implemented On Same Image:
Tested working in both Chrome and Firefox.
Just do this
write oncontextmenu on body tag
<body oncontextmenu="return false">
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('img').bind('contextmenu', function(e){
return false;
});
});//]]>
</script>
</head>
<body>
<img src="http://www.winergyinc.com/wp-content/uploads/2010/12/ajax.jpg"/>
</body>
Simple Way:
<body oncontextmenu="return false" onselectstart="return false" ondragstart="return false">
Do it like below (It works on firefox too):
$(document).on("contextmenu",function(e){
if( e.button == 2 ) {
e.preventDefault();
callYourownFucntionOrCodeHere();
}
return true;
});
I had used this code to disable right click in any web page, Its working fine. You can use this code
jQuery(document).ready(function(){
jQuery(function() {
jQuery(this).bind("contextmenu", function(event) {
event.preventDefault();
alert('Right click disable in this site!!')
});
});
});
<html>
<head>
<title>Right click disable in web page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
You write your own code
</body>
</html>
Of course, as per all other comments here, this simply doesn't work.
I did once construct a simple java applet for a client which forced any capture of of an image to be done via screen capture and you might like to consider a similar technique. It worked, within the limitations, but I still think it was a waste of time.
Put this code into your <head> tag of your page.
<script type="text/javascript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
This will disable right click on your whole web page, but only when JavaScript is enabled.
<script>
window.oncontextmenu = function () {
console.log("Right Click Disabled");
return false;
}
</script>
Try This
<script language=JavaScript>
//Disable right mouse click Script
var message="Function Disabled!";
function clickIE4(){
if (event.button==2){
alert(message);
return false;
}
}
function clickNS4(e){
if (document.layers||document.getElementById&&!document.all){
if (e.which==2||e.which==3){
alert(message);
return false;
}
}
}
if (document.layers){
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false")
</script>
Disabling right click on your web page is simple. There are just a few lines of JavaScript code that will do this job. Below is the JavaScript code:
$("html").on("contextmenu",function(e){
return false;
});
In the above code, I have selected the tag. After you add just that three lines of code, it will disable right click on your web page.
Source: Disable right click, copy, cut on web page using jQuery
There are three most popular following ways of disabling a right mouse click on your webpage.
#1 Using HTML Body Tag
<body oncontextmenu="return false;">
#2 Using CSS
body {
-webkit-user-select: none; /* Chrome all / Safari all */
-moz-user-select: none; /* Firefox all */
-ms-user-select: none; /* IE 10+ */
-o-user-select: none;
user-select: none;
}
#3 Using JavaScript
document.addEventListener('contextmenu', e => e.preventDefault());
I know I am late, but I want to create some assumptions and explainations for the answer I am going to provide.
Can I disable right-click
Can I disable right click on my web page without using Javascript?
Yes, by using JavaScript you can disable any event that happens and you can do that mostly only by javaScript. How, all you need is:
A working hardware
A website or somewhere from which you can learn about the keycodes. Because you're gonna need them.
Now lets say you wanna block the enter key press here is the code:
function prevententer () {
if(event.keyCode == 13) {
return false;
}
}
For the right click use this:
event.button == 2
in the place of event.keyCode. And you'll block it.
I want to ask this because most browsers allow users to disable it by Javascript.
You're right, browsers allow you to use JavaScript and javascript does the whole job for you. You donot need to setup anything, just need the script attribute in the head.
Why you should not disable it?
The main and the fast answer to that would be, users won't like it. Everyone needs freedom, no-one I mean no-one wants to be blocked or disabled, a few minutes ago I was at a site, which had blocked me from right clicking and I felt why? Do you need to secure your source code? Then here ctrl+shift+J I have opened the Console and now I can go to HTML-code tab. Go ahead and stop me. This won't add any of the security layer to your app.
There are alot of userful menus in the Right Click, like Copy, Paste, Search Google for 'text' (In Chrome) and many more. So user would like to get ease of access instead of remembering alot of keyboard shortcuts. Anyone can still copy the context, save the image or do whatever he wants.
Browsers use Mouse Navigation: Some browsers such as Opera uses mouse navigation, so if you disable it, user would definitely hate your User Interface and the scripts.
So that was the basic, I was going to write some more about saving the source code hehehe but, let it be the answer to your question.
Reference to the keycodes:
Key and mouse button code:
http://www.w3schools.com/jsref/event_button.asp
https://developer.mozilla.org/en-US/docs/Web/API/event.button (would be appreciated by the users too).
Why not to disable right click:
http://www.sitepoint.com/dont-disable-right-click/
Try this code for disabling inspect element option
jQuery(document).ready(function() {
function disableSelection(e) {
if (typeof e.onselectstart != "undefined") e.onselectstart = function() {
return false
};
else if (typeof e.style.MozUserSelect != "undefined") e.style.MozUserSelect = "none";
else e.onmousedown = function() {
return false
};
e.style.cursor = "default"
}
window.onload = function() {
disableSelection(document.body)
};
window.addEventListener("keydown", function(e) {
if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 67 || e.which == 70 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {
e.preventDefault()
}
});
document.keypress = function(e) {
if (e.ctrlKey && (e.which == 65 || e.which == 66 || e.which == 70 || e.which == 67 || e.which == 73 || e.which == 80 || e.which == 83 || e.which == 85 || e.which == 86)) {}
return false
};
document.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == 123 || e.keyCode == 18) {
return false
}
};
document.oncontextmenu = function(e) {
var t = e || window.event;
var n = t.target || t.srcElement;
if (n.nodeName != "A") return false
};
document.ondragstart = function() {
return false
};
});
$(document).ready(function () {
document.oncontextmenu = document.body.oncontextmenu = function () { return false; }
});
Important Note: It depends on browser and OS to allow such prevention or not!
Should you do it? No. Because it will not prevent the user, but it will just annoys him/her.
Can you use it? Yes. Examples: In some web-apps where you want to have customized pop-up menu, in-game where users might be annoyed when mistakenly they right-click, and other cases.
Chrome (v65) in Ubuntu 16.04 = You CAN disable right-click.
Chrome (v65) in Mac OS 10.11 = You CAN NOT disable right-click.
Chrome (v65) in Windows 7 = You CAN NOT disable right-click.
Firefox (v41) in Mac OS 10.11 = You CAN disable right-click.
Firefox (v43) in Windows 7 = You CAN disable right-click.
// Vanilla JS way
document.addEventListener('contextmenu', function(e){
e.preventDefault();
});
// jQuery way
$(document).bind('contextmenu', function(e) {
e.preventDefault();
});
A few things to consider:
Browser Plugins like "enable right click" in the chrome store exist for a reason, and you wont be able to get around them. There is LITERALLY NOTHING you can do to stop people from downloading your content as they literally have to download it to even see it in their browser anyway; People try but its always out there.
In general, if content shouldn't be public, don't put it online.
Also, not being able to right click is an accessibility issue and amounts to unlawful discrimination against the blind or disabled or elderly in many cases. Check you local laws, but in the USA its actively against the law in the form of the Federal ADA as the blind or the elderly who may have vision issues are a legally protected class.
So instead of doing this and wasting a lot of time and effort, don't even bother trying to do this. It could just get your company sued or have them fail a compliance audit.
Yes, you can disable it using HTML and Javascript.
Just add oncontextmenu="return false;" on your body or element.
It is very simple and just uses valid HTML and Javascript, no jQuery.
Javascript:
document.getElementsByTagName("html")[0].setAttribute("oncontextmenu", "return false");
I'd like to add a note (for chrome 97) not sure if this is a bug related to chrome or my environment.
Right clicking on a specific element of my application opens a page in a new tab, using mousedown and oncontextmenu="return false" I was still having the contextual menu appearing, even on the new opened page (Only the menus of installed chrome extensions appear on that contextual menu, I think this "bug" should get fixed in future version of the browsers).
But in the meantime I fixed it using this simple hack
function onMouseDown () {
setTimeout(() => window.open('the link', '_blank'), 100)
}
I am just deferring the tab opening. I think this bug occurs because the right click is caught by the new opened page, not from the original page of my application that tries to open the tab.
Hope it saves you from headaches.
Use this function to disable right click.You can disable left click and tap also by checking 1 and 0 corresponding
document.onmousedown = rightclickD;
function rightclickD(e)
{
e = e||event;
console.log(e);
if (e.button == 2) {
//alert('Right click disabled!!!');
return false; }
}

Categories

Resources