I am trying to create a cross browser javascript that detects whether or not the visitor is using Incognito Mode, and gives a alert message if the user visits the page in normal mode.
Currently I have a script, that works just fine on Chrome and Opera, But I need to get it work on all the other browsers as well like firefox, safari, Edge etc.
My script (Working on Chrome and Opera) is:
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
function main() {
var fs = window.RequestFileSystem || window.webkitRequestFileSystem;
if (!fs) {
alert("check failed!");
return;
}
fs(window.TEMPORARY, 100, function(fs) {
alert("You are not using Incognito Mode!");
});
}
main();
}//]]> </script>
Please help me write a single script like this to give the same alert results in all the major web browsers.
Thanks
UPDATE:
I've finally made a working script for Firefox as well. The code is as follows:
<script type='text/javascript'>
var db;
var request = indexedDB.open("MyTestDatabase");
request.onsuccess = function(event) {
if (navigator.userAgent.indexOf("Firefox") != -1)
{
alert("You are not using Incognito Mode!");
};
};</script>
I've used the "if (navigator.userAgent.indexOf("Firefox") != -1)" function so that it executes only on firefox, and not in chrome or any other browser.
UPDATE:
Ok another accomplishment! I've successfully written the script for Safari as well. Here it is:
<script type='text/javascript'>
try { localStorage.test = 2; } catch (e) {
}
if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0)
{
if (localStorage.test = "true") {
alert("You are not using Incognito Mode!");
}
}
</script>
Again, I've used "if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0)" function so that it executes only on Safari, and not in any other browser.
Now I need help in writing script only for Edge browser.
There is this solution I found here:
I just copied it below in case it gets removed.
function retry(isDone, next) {
var current_trial = 0, max_retry = 50, interval = 10, is_timeout = false;
var id = window.setInterval(
function() {
if (isDone()) {
window.clearInterval(id);
next(is_timeout);
}
if (current_trial++ > max_retry) {
window.clearInterval(id);
is_timeout = true;
next(is_timeout);
}
},
10
);
}
function isIE10OrLater(user_agent) {
var ua = user_agent.toLowerCase();
if (ua.indexOf('msie') === 0 && ua.indexOf('trident') === 0) {
return false;
}
var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(ua);
if (match && parseInt(match[1], 10) >= 10) {
return true;
}
return false;
}
function detectPrivateMode(callback) {
var is_private;
if (window.webkitRequestFileSystem) {
window.webkitRequestFileSystem(
window.TEMPORARY, 1,
function() {
is_private = false;
},
function(e) {
console.log(e);
is_private = true;
}
);
} else if (window.indexedDB && /Firefox/.test(window.navigator.userAgent)) {
var db;
try {
db = window.indexedDB.open('test');
} catch(e) {
is_private = true;
}
if (typeof is_private === 'undefined') {
retry(
function isDone() {
return db.readyState === 'done' ? true : false;
},
function next(is_timeout) {
if (!is_timeout) {
is_private = db.result ? false : true;
}
}
);
}
} else if (isIE10OrLater(window.navigator.userAgent)) {
is_private = false;
try {
if (!window.indexedDB) {
is_private = true;
}
} catch (e) {
is_private = true;
}
} else if (window.localStorage && /Safari/.test(window.navigator.userAgent)) {
try {
window.localStorage.setItem('test', 1);
} catch(e) {
is_private = true;
}
if (typeof is_private === 'undefined') {
is_private = false;
window.localStorage.removeItem('test');
}
}
retry(
function isDone() {
return typeof is_private !== 'undefined' ? true : false;
},
function next(is_timeout) {
callback(is_private);
}
);
}
Related
I am testing twoway-motion.js on Aframe, by providing a simple way to navigate specifically without a device orientation permission from a mobile phone.
please check this glitch page for details: https://glitch.com/~scrawny-efraasia
also please see twoway-motion.js by #flowerio
AFRAME.registerComponent('twoway-motion', {
schema: {
speed: { type: "number", default: 40 },
threshold: { type: "number", default: -40 },
nonMobileLoad: { type: "boolean", default: false },
removeCheckpoints: {type: "boolean", default: true },
chatty: {type: "boolean", default: true }
},
init: function () {
var twowaymotion = document.querySelector("[camera]").components["twoway-motion"];
twowaymotion.componentName = "twoway-motion";
report = function(text) {
if (twowaymotion.data.chatty) {
console.log(twowaymotion.componentName, ":", text);
}
}
report("init.");
// report("asked to load with speed=", this.data.speed);
if (!AFRAME.utils.device.isMobile() && this.data.nonMobileLoad === false) {
// this is only for mobile devices.
//document.querySelector("[camera]").removeAttribute("twoway-motion");
report("Retired. Will only work on mobile.");
return;
} else {
if (this.data.nonMobileLoad === true) {
report("Loading on non-mobile platform.");
}
}
if (this.el.components["wasd-controls"] === undefined) {
this.el.setAttribute("wasd-controls", "true");
report("Installing wasd-controls.");
}
this.el.components["wasd-controls"].data.acceleration = this.data.speed;
// two-way hides checkpoint-controls by default.
if (this.data.removeCheckpoints) {
if (this.el.components["checkpoint-controls"] !== undefined) {
var checkpoints = document.querySelectorAll("[checkpoint]");
for (var cp = 0; cp < checkpoints.length; cp++) {
checkpoints[cp].setAttribute("visible", false);
}
}
}
this.el.removeAttribute("universal-controls");
if (this.el.components["look-controls"] === undefined) {
this.el.setAttribute("look-controls", "true");
}
var cur = document.querySelector("[cursor]");
if (cur !== null) {
console.log(this.componentName, ": found a cursor.");
this.cur = cur;
//this.curcolor = cur.getAttribute("material").color;
this.curcolor = cur.getAttribute("color");
} else {
console.log(this.componentName, ": didn't find a cursor.");
}
var canvas = document.querySelector(".a-canvas");
canvas.addEventListener("mousedown", function (e) {
report("mousedown", e);
twowaymotion.touching = true;
this.touchTime = new Date().getTime();
});
canvas.addEventListener("mouseup", function (e) {
report("mouseup", e);
twowaymotion.touching = false;
});
canvas.addEventListener("touchstart", function (e) {
this.touch = e;
report("touches.length: ", e.touches.length);
if (e.touches.length > 1) {
report("multitouch: doing nothing");
} else {
report("touchstart", e);
twowaymotion.touching = true;
}
});
canvas.addEventListener("touchend", function () {
console.log(this.componentName, " touchend");
twowaymotion.touching = false;
});
},
update: function() {
if (this.el.components["twoway-controls"] !== undefined) {
this.el.components["wasd-controls"].data.acceleration = this.el.components["wasd-controls"].data.speed;
}
},
tick: function () {
if (!AFRAME.utils.device.isMobile() && this.data.nonMobileLoad === false) {
// this is only for mobile devices, unless you ask for it.
return;
}
if (!this.isPlaying) {
return;
}
var cam = this.el;
var camrot = cam.getAttribute("rotation");
if (camrot.x < this.data.threshold) {
// we are looking down
if (this.cur !== null && this.cur !== undefined) {
this.cur.setAttribute("material", "color", "orange");
}
if (this.touching === true) {
cam.components["wasd-controls"].keys["ArrowDown"] = true;
} else {
cam.components["wasd-controls"].keys["ArrowDown"] = false;
cam.components["wasd-controls"].keys["ArrowUp"] = false;
}
} else {
// we are looking forward or up
if (this.cur !== null && this.cur !== undefined) {
this.cur.setAttribute("material", "color", this.curcolor);
}
if (this.touching === true) {
cam.components["wasd-controls"].keys["ArrowUp"] = true;
} else {
cam.components["wasd-controls"].keys["ArrowDown"] = false;
cam.components["wasd-controls"].keys["ArrowUp"] = false;
}
}
},
pause: function () {
// we get isPlaying automatically from A-Frame
},
play: function () {
// we get isPlaying automatically from A-Frame
},
remove: function () {
if (this.el.components["wasd-controls"] === undefined) {
this.el.removeAttribute("wasd-controls");
}
} });
Since device orientation permission is not granted on mobile phones, move backward is not working, also, when the audience tries to rotate in a different direction by touching the screen or sliding on screen, it still functions as move forward.
from what I imagine, if there is a simple edit, if the audience touches the screen more than 2 seconds, it start to move forward, if audience just rotate, it will not move forward, since when you slide or touch on the screen to rotate the touching time might not be so long as 2 seconds...
this is the easiest solution that I can imagine under the restriction of without device orientation permission.
or is there any other better way to divide rotate and move forward by touching screen regarding touching time?
Thks!!!!!
I have a code to avoid users opening devtools menu, the code works perfectly for me! But sometimes, when you watch a simple video at my website and put it on fullscreen, the script below returns false positive.
// chrome
var element = new Image;
var devtoolsOpen = false;
element.__defineGetter__("id", function() {
devtoolsOpen = true; // This only executes when devtools is open.
});
setInterval(function() {
devtoolsOpen = false;
//console.log(element);
if (devtoolsOpen && devtoolsOpen == true) {
window.location = "https://mywebsite.com/denied/";
}
}, 1000);
// all
var _interval = 200;
(function() {
'use strict';
var devtools = {
open: false,
orientation: null
};
var threshold = 160;
var emitEvent = function(state, orientation) {
window.dispatchEvent(new CustomEvent('devtoolschange', {
detail: {
open: state,
orientation: orientation
}
}));
};
setInterval(function() {
var widthThreshold = window.outerWidth - window.innerWidth > threshold;
var heightThreshold = window.outerHeight - window.innerHeight > threshold;
var orientation = widthThreshold ? 'vertical' : 'horizontal';
if (!(heightThreshold && widthThreshold) &&
((window.Firebug && window.Firebug.chrome && window.Firebug.chrome.isInitialized) || widthThreshold || heightThreshold)) {
if (!devtools.open || devtools.orientation !== orientation) {
emitEvent(true, orientation);
}
devtools.open = true;
devtools.orientation = orientation;
} else {
if (devtools.open) {
emitEvent(false, null);
}
devtools.open = false;
devtools.orientation = null;
}
}, _interval);
if (typeof module !== 'undefined' && module.exports) {
module.exports = devtools;
} else {
window.devtools = devtools;
}
setTimeout(function() {
_interval = 500;
}, 1000);
})();
// check if it's open
//console.log('is DevTools open?', window.devtools.open);
if (window.devtools.open && window.devtools.open == true) {
window.location = "https://mywebsite.com/denied/";
}
// get notified when it's opened/closed or orientation changes
window.addEventListener('devtoolschange', function(e) {
//console.log('is DevTools open?', e.detail.open);
if (e.detail.open && e.detail.open == true) {
window.location = "https://mywebsite.com/denied/";
}
});
// clear
console.API;
if (typeof console._commandLineAPI !== 'undefined') {
console.API = console._commandLineAPI; //chrome
} else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
console.API = console._inspectorCommandLineAPI; //Safari
} else if (typeof console.clear !== 'undefined') {
console.API = console;
}
console.API.clear();
I reviewed the code many times and I wasn't able to find why this is happening. Do you have any idea about how can I solve it?
Thank you.
It seems like the old detection methods which have worked for iOS 11 and respective Safari version(s) do not work anymore.
I have tried this script: https://gist.github.com/cou929/7973956
But it doesn't work for safari on iOS 12 and also doesn't work for Chrome 69 on iOS 12.
This quite new library is also not working for iOS 12 browsers:
https://github.com/Maykonn/js-detect-incognito-private-browsing-paywall
So is there any solution for iOS 12 browsers yet?
BostonGlobe seems to have a solution, but I have no idea how they did it:
https://www.bostonglobe.com/sports/redsox/2018/10/09/redsox/D66J59viZ1qxyZlhI18l8L/story.html
(If you want to read an BostonGlobe.com article in incognito / private mode you get a screen which asks you to log in)
Chrome Devtools => The module to detect incognito/private mode is called "detect-private-browsing" located at webpack:///./~/detect-private-browsing/index.js
// ./~/detect-private-browsing/index.js
function retry(isDone, next) {
var current_trial = 0, max_retry = 50, interval = 10, is_timeout = false;
var id = window.setInterval(
function() {
if (isDone()) {
window.clearInterval(id);
next(is_timeout);
}
if (current_trial++ > max_retry) {
window.clearInterval(id);
is_timeout = true;
next(is_timeout);
}
},
10
);
}
function isIE10OrLater(user_agent) {
var ua = user_agent.toLowerCase();
if (ua.indexOf('msie') === 0 && ua.indexOf('trident') === 0) {
return false;
}
var match = /(?:msie|rv:)\s?([\d\.]+)/.exec(ua);
if (match && parseInt(match[1], 10) >= 10) {
return true;
}
// MS Edge Detection from this gist: https://gist.github.com/cou929/7973956
var edge = /edge/.exec(ua);
if (edge && edge[0] == "edge") {
return true;
}
return false;
}
module.exports = {
detectPrivateMode: function(callback) {
var is_private;
if (window.webkitRequestFileSystem) {
window.webkitRequestFileSystem(
window.TEMPORARY, 1,
function() {
is_private = false;
},
function(e) {
console.log(e);
is_private = true;
}
);
} else if (window.indexedDB && /Firefox/.test(window.navigator.userAgent)) {
var db;
try {
db = window.indexedDB.open('test');
} catch(e) {
is_private = true;
}
if (typeof is_private === 'undefined') {
retry(
function isDone() {
return db.readyState === 'done' ? true : false;
},
function next(is_timeout) {
if (!is_timeout) {
is_private = db.result ? false : true;
}
}
);
}
} else if (isIE10OrLater(window.navigator.userAgent)) {
is_private = false;
try {
if (!window.indexedDB) {
is_private = true;
}
} catch (e) {
is_private = true;
}
} else if (window.localStorage && /Safari/.test(window.navigator.userAgent)) {
// One-off check for weird sports 2.0 polyfill
// This also impacts iOS Firefox and Chrome (newer versions), apparently
// #see bglobe-js/containers/App.js:116
if (window.safariIncognito) {
is_private = true;
} else {
try {
window.openDatabase(null, null, null, null);
} catch (e) {
is_private = true;
}
try {
window.localStorage.setItem('test', 1);
} catch(e) {
is_private = true;
}
}
if (typeof is_private === 'undefined') {
is_private = false;
window.localStorage.removeItem('test');
}
}
retry(
function isDone() {
return typeof is_private !== 'undefined' ? true : false;
},
function next(is_timeout) {
callback(is_private);
}
);
}
};
//FOR IOS 12
var e = false;
if (window.localStorage && /Safari/.test(window.navigator.userAgent)) {
if (window.safariIncognito) {
e = true;
} else {
try {
window.openDatabase(null, null, null, null);
window.localStorage.setItem("test", 1)
} catch (t) {
e = true;
alert("PRIVATE");
}
}
void !e && (e = !1, window.localStorage.removeItem("test"))
}
I looking for some pointer on how data is sent using a custom library that connects to a java server running as a websocket server.
The code im using to connect which is successful
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="b4j_ws.js"></script>
<script>
// connection to websocket
$( document ).ready(function() {
b4j_connect("/push/ws");
});
</script>
and this is my guess and how to send data using the library which at the moment is not correct, the message would be 'wwww' when sent successfully.
<script>
b4j_ws.send(JSON.stringify({"type":"data","data":"wwww"}));
</script>
These are frames i captured from the working example but it used a button where i want to just use jquery
{"type":"event","event":"btnsend_click","params":{"which":1,"target":"btnsend","pageX":31,"pageY":19,"metaKey":false}}
{"id":"#txt","method":"val","etype":"runmethodWithResult"}
{"type":"data","data":"wwww"}
the library which is b4j_ws.js in the above code.
//B4J WebSockets client library v0.9
/*jslint browser: true*/
/*global $, jQuery, WebSocket*/
/*jshint curly: false */
"use strict";
var b4j_ws;
var b4j_closeMessage = false;
//only called as a result of a server request that is waiting for result.
//this method should not be called in any other case.
function b4j_sendData(data) {
b4j_ws.send(JSON.stringify({type: "data", data: data}));
}
function b4j_raiseEvent(eventName, parameters) {
try {
if (b4j_ws.readyState !== 1) {
if (b4j_closeMessage === false) {
window.console.error("connection is closed.");
window.alert("Connection is closed. Please refresh the page to reconnect.");
b4j_closeMessage = true;
}
} else {
b4j_ws.send(JSON.stringify({type: "event", event: eventName, params: parameters}));
}
} catch (e) {
window.console.error(e);
}
}
function b4j_addEvent(selector, event, eventName, preventDefault) {
var obj = $(selector);
if (obj.length > 0) {
obj.on(event, function (e) {
if (preventDefault) {
e.preventDefault();
e.stopPropagation();
}
b4j_raiseEvent(eventName, {which: e.which, target: e.target.id, pageX: e.pageX, pageY: e.pageY, metaKey: e.metaKey});
});
}
}
function b4j_addAutomaticEvents(data) {
$.each(data, function (index, value) {
b4j_addEvent("#" + value.id, value.event, value.id + "_" + value.event, true);
});
}
function b4j_runFunction(func, params) {
return window[func].apply(null, params);
}
function b4j_eval(params, script) {
var f = new Function(script);
return f.apply(null, params);
}
function b4j_connect(absolutePath) {
if (typeof WebSocket === 'undefined') {
window.alert("WebSockets are not supported by your browser.");
return;
}
var l = window.location, fullpath;
fullpath = ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + ":" + l.port + absolutePath;
b4j_ws = new WebSocket(fullpath);
b4j_ws.onmessage = function (event) {
var ed = JSON.parse(event.data);
if (ed.etype === "runmethod") {
$(ed.id)[ed.method].apply($(ed.id), ed.params);
} else if (ed.etype === "runmethodWithResult") {
b4j_sendData($(ed.id)[ed.method].apply($(ed.id), ed.params));
} else if (ed.etype === "setAutomaticEvents") {
b4j_addAutomaticEvents(ed.data);
} else if (ed.etype === "runFunction") {
b4j_runFunction(ed.prop, ed.value);
} else if (ed.etype === "runFunctionWithResult") {
b4j_sendData(b4j_runFunction(ed.prop, ed.value));
} else if (ed.etype === "eval") {
b4j_eval(ed.value, ed.prop);
} else if (ed.etype === "evalWithResult") {
b4j_sendData(b4j_eval(ed.value, ed.prop));
} else if (ed.etype === "alert") {
window.alert(ed.prop);
}
};
}
I change on the click method to a onload method in the java webserver and it worked!
i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.