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!!!!!
Related
I have to switch camera in webrtc when 2 user connecting in the call. I'm having a problem trying to change my camera in real time, It works for the local video, but the remote person cannot see the new camera, and still sees the old one. I tried to stop the stream and init again but still not working. This is just some of my code. I have searched everywhere and I can't find a solution. Can someone help me out?
``
$(".btn_rear_camera").click(function() {
if (cameratype == "user") {
capture('environment');
} else {
capture('user');
}
});
function capture(facingMode) {
cameratype = facingMode;
localStream.getTracks().forEach(function(track) {
track.stop();
});
var constraints = {
video: {
deviceId: devicesIds[1]
},
audio: true
};
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
replaceTracks(stream);
}).catch(function(error) {
});
}
function replaceTracks(newStream) {
var elementId = "localVideo";
detachMediaStream(elementId);
newStream.getTracks().forEach(function(track) {
localStream.addTrack(track);
});
attachMediaStream(elementId, newStream);
// optionally, if you have active peer connections:
_replaceTracksForPeer(peerConnection);
function _replaceTracksForPeer(peer) {
peer.getSenders().map(function(sender) {
sender.replaceTrack(newStream.getTracks().find(function(track) {
return track.kind === sender.track.kind;
}));
});
}
}
function detachMediaStream(id) {
var elem = document.getElementById(id);
if (elem) {
elem.pause();
if (typeof elem.srcObject === 'object') {
elem.srcObject = null;
} else {
elem.src = '';
}
}
};
function attachMediaStream(id, stream) {
var elem = document.getElementById(id);
if (elem) {
if (typeof elem.srcObject === 'object') {
elem.srcObject = stream;
} else {
elem.src = window.URL.createObjectURL(stream);
}
elem.onloadedmetadata = function(e) {
elem.play();
};
} else {
throw new Error('Unable to attach media stream');
}
};
``
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"))
}
JSFiddle
https://jsfiddle.net/wz9ghpnc/
Issue
Using: latest jQuery
Why this lagging to much on mobile devices? I'm really done with trying to optimize this.
How can I apply something like debounce / throttling? I tried to add setTimeout to move() function with 50 ms delay but that was laggy too.
Moving on mobile is so laggy... animations are too so laggy...
let $state = {
afterDown: {
clientX: 0,
scrollLeft: 0,
},
afterUp: {
clientX: 0,
scrollLeft: 0,
},
dreamedScrollLeft: 0,
isDown: false,
};
let centering = false;
let duration = 250;
let messages = false;
function message () {
if (messages === true) {
console.log('%c addScroll ', 'background: #000; color: #fff;', ...arguments);
}
}
// Events
function down (parent) {
return (event) => {
message('down');
if ($state.isDown === false) {
$state.afterDown.clientX = event.originalEvent.touches ? event.originalEvent.touches[0].clientX : event.clientX;
$state.afterDown.scrollLeft = $(parent).scrollLeft();
$(parent).stop();
$state.isDown = true;
}
};
}
function leave (parent) {
return () => {
message('leave');
if ($state.isDown === true) {
$(parent).removeClass('scroll-moving');
$state.isDown = false;
}
};
}
function move (parent) {
return (event) => {
message('move');
if ($state.isDown === true) {
$(parent).addClass('scroll-moving');
const clientX = event.originalEvent.touches ? event.originalEvent.touches[0].clientX : event.clientX;
$(parent).scrollLeft($state.afterDown.clientX + $state.afterDown.scrollLeft - clientX);
}
};
}
function scroll (parent) {
return () => {
message('scroll');
if (centering === true) {
if ($(parent).scrollLeft() === $state.dreamedScrollLeft) {
message('after scroll centering');
if (centering === true) {
if ($(parent).scrollLeft() === $state.dreamedScrollLeft) {
message('after scroll centering');
}
}
}
}
};
}
function up (parent) {
return (event) => {
message('up');
if ($state.isDown === true) {
$(parent).removeClass('scroll-moving');
$state.afterUp.clientX = event.originalEvent.changedTouches ? event.originalEvent.changedTouches[0].clientX : event.clientX;
$state.afterUp.scrollLeft = $(parent).scrollLeft();
if ($state.afterDown.clientX > $state.afterUp.clientX) {
message('👉 moving right');
$state.dreamedScrollLeft = $(parent).scrollLeft() + ($state.afterDown.clientX - $state.afterUp.clientX);
}
if ($state.afterUp.clientX > $state.afterDown.clientX) {
message('👈 moving left');
$state.dreamedScrollLeft = $(parent).scrollLeft() - ($state.afterUp.clientX - $state.afterDown.clientX);
}
$(parent).animate({ scrollLeft: $state.dreamedScrollLeft, }, duration, 'linear');
message($state.afterDown, $state.afterUp, $state.dreamedScrollLeft);
$state.isDown = false;
}
};
}
$.fn.extend({
addScroll: function (i) {
if (i.centering) {
centering = i.centering;
}
if (i.duration) {
duration = i.duration;
}
if (i.messages) {
messages = i.messages;
}
$(this).css('overflow', 'hidden');
$(this).bind('mousedown touchstart', down(this));
$(this).bind('mouseleave', leave(this));
$(this).bind('mousemove touchmove', move(this));
$(this).bind('scroll', scroll(this));
$(this).bind('mouseup touchend', up(this));
},
});
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);
}
);
}