Avoid DevTools menu - javascript

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.

Related

Aframe movement control on mobile phone regarding to twoway-motion.js

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!!!!!

Private / Incognito Mode Detection for iOS 12 Safari

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"))
}

Javascript For Cross Browser Detection of Incognito Mode (Private Browsing)

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);
}
);
}

Tiled Map Editor using Phaser to make a Maze

I'm trying to create a Maze game using the Tiled map editor and Phaser. I am using this tutorial as a base: http://phaser.io/tutorials/coding-tips-005
But my map is not showing in my browser. I have created a tilemap and exported it as a json file. And there is an error in the code saying Uncaught ReferenceError: Phaser is not defined". What am I missing or doing incorrectly?
This is the code:
<!DOCTYPE HTML>
<html>
<head>
<title>Maze Game</title>
<meta charset="utf-8">
<script src="//cdn.jsdelivr.net/phaser/2.2.2/phaser.min.js"></script>
</head>
<body>
<div id="game"></div>
<script type="text/javascript">
var game = new Phaser.Game(640, 480, Phaser.AUTO, 'game');
var PhaserGame = function (game) {
this.map = null;
this.layer = null;
this.car = null;
this.safetile = 1;
this.gridsize = 32;
this.speed = 150;
this.threshold = 3;
this.turnSpeed = 150;
this.marker = new Phaser.Point();
this.turnPoint = new Phaser.Point();
this.directions = [ null, null, null, null, null ];
this.opposites = [ Phaser.NONE, Phaser.RIGHT, Phaser.LEFT, Phaser.DOWN, Phaser.UP ];
this.current = Phaser.UP;
this.turning = Phaser.NONE;
};
PhaserGame.prototype = {
init: function () {
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
// We need this because the assets are on Amazon S3
// Remove the next 2 lines if running locally
this.load.baseURL = 'http://files.phaser.io.s3.amazonaws.com/codingtips/issue005/';
this.load.crossOrigin = 'anonymous';
this.load.tilemap('map', 'assets/samplemaze.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('tiles', 'assets/tiles.png');
this.load.image('car', 'assets/car.png');
// Note: Graphics are Copyright 2015 Photon Storm Ltd.
},
create: function () {
this.map = this.add.tilemap('map');
this.map.addTilesetImage('tiles', 'tiles');
this.layer = this.map.createLayer('Tile Layer 1');
this.map.setCollision(20, true, this.layer);
this.car = this.add.sprite(48, 48, 'car');
this.car.anchor.set(0.5);
this.physics.arcade.enable(this.car);
this.cursors = this.input.keyboard.createCursorKeys();
this.move(Phaser.DOWN);
},
checkKeys: function () {
if (this.cursors.left.isDown && this.current !== Phaser.LEFT)
{
this.checkDirection(Phaser.LEFT);
}
else if (this.cursors.right.isDown && this.current !== Phaser.RIGHT)
{
this.checkDirection(Phaser.RIGHT);
}
else if (this.cursors.up.isDown && this.current !== Phaser.UP)
{
this.checkDirection(Phaser.UP);
}
else if (this.cursors.down.isDown && this.current !== Phaser.DOWN)
{
this.checkDirection(Phaser.DOWN);
}
else
{
// This forces them to hold the key down to turn the corner
this.turning = Phaser.NONE;
}
},
checkDirection: function (turnTo) {
if (this.turning === turnTo || this.directions[turnTo] === null || this.directions[turnTo].index !== this.safetile)
{
// Invalid direction if they're already set to turn that way
// Or there is no tile there, or the tile isn't index a floor tile
return;
}
// Check if they want to turn around and can
if (this.current === this.opposites[turnTo])
{
this.move(turnTo);
}
else
{
this.turning = turnTo;
this.turnPoint.x = (this.marker.x * this.gridsize) + (this.gridsize / 2);
this.turnPoint.y = (this.marker.y * this.gridsize) + (this.gridsize / 2);
}
},
turn: function () {
var cx = Math.floor(this.car.x);
var cy = Math.floor(this.car.y);
// This needs a threshold, because at high speeds you can't turn because the coordinates skip past
if (!this.math.fuzzyEqual(cx, this.turnPoint.x, this.threshold) || !this.math.fuzzyEqual(cy, this.turnPoint.y, this.threshold))
{
return false;
}
this.car.x = this.turnPoint.x;
this.car.y = this.turnPoint.y;
this.car.body.reset(this.turnPoint.x, this.turnPoint.y);
this.move(this.turning);
this.turning = Phaser.NONE;
return true;
},
move: function (direction) {
var speed = this.speed;
if (direction === Phaser.LEFT || direction === Phaser.UP)
{
speed = -speed;
}
if (direction === Phaser.LEFT || direction === Phaser.RIGHT)
{
this.car.body.velocity.x = speed;
}
else
{
this.car.body.velocity.y = speed;
}
this.add.tween(this.car).to( { angle: this.getAngle(direction) }, this.turnSpeed, "Linear", true);
this.current = direction;
},
getAngle: function (to) {
// About-face?
if (this.current === this.opposites[to])
{
return "180";
}
if ((this.current === Phaser.UP && to === Phaser.LEFT) ||
(this.current === Phaser.DOWN && to === Phaser.RIGHT) ||
(this.current === Phaser.LEFT && to === Phaser.DOWN) ||
(this.current === Phaser.RIGHT && to === Phaser.UP))
{
return "-90";
}
return "90";
},
update: function () {
this.physics.arcade.collide(this.car, this.layer);
this.marker.x = this.math.snapToFloor(Math.floor(this.car.x), this.gridsize) / this.gridsize;
this.marker.y = this.math.snapToFloor(Math.floor(this.car.y), this.gridsize) / this.gridsize;
// Update our grid sensors
this.directions[1] = this.map.getTileLeft(this.layer.index, this.marker.x, this.marker.y);
this.directions[2] = this.map.getTileRight(this.layer.index, this.marker.x, this.marker.y);
this.directions[3] = this.map.getTileAbove(this.layer.index, this.marker.x, this.marker.y);
this.directions[4] = this.map.getTileBelow(this.layer.index, this.marker.x, this.marker.y);
this.checkKeys();
if (this.turning !== Phaser.NONE)
{
this.turn();
}
},
render: function () {
// Un-comment this to see the debug drawing
for (var t = 1; t < 5; t++)
{
if (this.directions[t] === null)
{
continue;
}
var color = 'rgba(0,255,0,0.3)';
if (this.directions[t].index !== this.safetile)
{
color = 'rgba(255,0,0,0.3)';
}
if (t === this.current)
{
color = 'rgba(255,255,255,0.3)';
}
this.game.debug.geom(new Phaser.Rectangle(this.directions[t].worldX, this.directions[t].worldY, 32, 32), color, true);
}
this.game.debug.geom(this.turnPoint, '#ffff00');
}
};
game.state.add('Game', PhaserGame, true);
</script>
<img src="http://files.phaser.io.s3.amazonaws.com/codingtips/issue005/phaser-tips-header1.png" title="Phaser Coding Tips Weekly" style="margin-top: 8px" />
</body>
</html>
Thank you so much! I'm pretty new to programming so any feedback would be very useful!
You might be missing "http:" or "https:" in your script tag's src attribute. If so, then the phaser.min.js file isn't being included in your page and could result in undefined references.

Force link to open in same window/tab

I am using google chrome with this extension - Open Link in Same Tab.
It's very simple and basically does what it says, forces all links to open in the same window/tab. I require this functionality for touch screen kiosk left/right swipe navigation.
The plugin works very well when it comes to links. However it doesn't work when a search is performed in a 'submit' web search form. Presumably because the extension is forcing anything with _blank to open in _top, but it's ignoring forms.
How can I modify the extension in such a way that it also takes into consideration forms, and forces these to also open in the same tab?
I have downloaded the extension and viewed the code, the main js seems to be in the sametab.js file. I have included this below, I'm sure I can modify it somehow to fit my needs.
Any help is appreciated.
"use strict";
// "_blank|_self|_parent|_top|framename"; "framename" should not start with "_"
// - list of iframe names only contains the names of iframes and not the names
// of windows in other tabs that could be targets
// - list of iframe names is not updated if an iframe's name changes
(function() {
var sameTab = {
converted: false,
observer: null,
iframeNameList: [],
index: -1,
mutationObserverFunction: function(mutations, observer) {
sameTab.observer.disconnect();
mutations.forEach(function(mutation) {
var i, node, target;
target = mutation.target;
if (!document.contains(target)) return;
switch (mutation.type) {
case "attributes":
if (mutation.attributeName !== "target" ||
target.tagName !== "A") return;
target.onclick = (target.target === "" ||
target.target[0] === '_') ? "" : sameTab.doNamedTarget;
if (target.target.toLowerCase() !== "_blank" ||
mutation.oldValue === "_top") return;
target.target = "_top";
break;
case "childList":
for (i = 0; i < mutation.addedNodes.length; i++) {
node = mutation.addedNodes[i];
if (node.parentNode !== target || node.nodeType !=
document.ELEMENT_NODE) continue;
sameTab.convertLinks(node);
}
break;
}
});
sameTab.observeDocument();
},
observeDocument: function() {
sameTab.observer.observe(document, {
childList: true,
subtree: true,
characterData: false,
attributes: true,
attributeOldValue: true,
attributeFilter: ["target"]
});
},
convertDocument: function(eventObject) {
sameTab.convertLinks(document);
sameTab.observer = new MutationObserver(sameTab.mutationObserverFunction);
sameTab.observeDocument();
sameTab.converted = true;
},
// When a link with a named target is clicked, change the target to "_top"
// unless the name is in the list of iframe names.
doNamedTarget: function(eventObject) {
// First make sure the iframe's own name is correct.
if (sameTab.index !== -1) {
sameTab.iframeNameList[sameTab.index] === window.name;
}
// Do nothing if the target name is in the list of window names.
if (sameTab.iframeNameList.indexOf(eventObject.target.target) !== -1) return;
eventObject.target.target = "_top";
},
// If the link target is "_blank" change it to "_top". If it is a name
// which does not begin with "_" set the link's click event handler so
// the list of iframe names can be checked for the target when the link is
// clicked.
convertLinks: function(node) {
var i, linkElements;
linkElements = node.querySelectorAll("a[target]");
for (i = 0; i < linkElements.length; i++) {
if (linkElements[i].target === "") continue;
if (linkElements[i].target[0] !== "_") {
linkElements[i].onclick = sameTab.doNamedTarget;
} else if (linkElements[i].target.toLowerCase() === "_blank") {
linkElements[i].target = "_top";
}
}
if (node.tagName !== "A" || node.target === "") return;
if (node.target[0] !== "_") {
node.onclick = sameTab.doNamedTarget;
} else if (node.target.toLowerCase() === "_blank") {
node.target = "_top";
}
}
};
var frame = null;
if (window === top) {
// Top frame
frame = {
iframeList: [],
convertAllLinks: false,
hostname: null,
// Delete an item from the list of iframes.
removeDeletedIframes: function(source) {
var i;
for (i = frame.iframeList.length - 1; i >= 0; i--) {
if (frame.iframeList[i].source && (!source ||
frame.iframeList[i].source !== source)) continue;
frame.iframeList.splice(i, 1);
sameTab.iframeNameList.splice(i, 1);
}
},
sendIframeList: function(source) {
var i, len, origin;
// First remove any deleted iframes from the lists.
frame.removeDeletedIframes(source);
len = frame.iframeList.length;
for (i = 0; i < len; i++) {
origin = (frame.iframeList[i].origin === "null") ?
"*" : frame.iframeList[i].origin;
frame.iframeList[i].source.postMessage({
senderId: "sameTabExtensionTop",
message: "nameList",
iframeNameList: sameTab.iframeNameList,
index: i,
}, origin);
}
},
checkLists: function(items) {
var i;
if (!items.settingsInitialized) {
console.warn("Stored data missing.");
window.removeEventListener("message", frame.windowMessages, false);
frame.iframeList.length = 0;
sameTab.iframeNameList.length = 0;
} else if (!items.convertLinks ||
(items.useWhitelist &&
items.whitelist.indexOf(frame.hostname) == -1) ||
items.blacklist.indexOf(frame.hostname) != -1) {
window.removeEventListener("message", frame.windowMessages, false);
frame.iframeList.length = 0;
sameTab.iframeNameList.length = 0;
} else {
frame.convertAllLinks = true;
frame.sendIframeList();
if (document.readyState === "interactive" ||
document.readyState === "complete") {
sameTab.convertDocument(null);
} else {
document.addEventListener("DOMContentLoaded",
sameTab.convertDocument, false);
}
}
},
getHostname: function() {
switch (location.protocol) {
case "file:":
return "file://" + location.hostname + location.pathname;
break;
case "http:":
case "https:":
return location.hostname;
break;
default:
return null;
break;
}
},
windowMessages: function(eventObject) {
var i, len;
if (!eventObject.data ||
eventObject.data.senderId !== "sameTabExtensionIframe") return;
switch (eventObject.data.message) {
case "windowUnloaded":
frame.sendIframeList(eventObject.source);
break;
case "contentLoaded":
if (!eventObject.source ||
eventObject.source.top !== window) return;
len = frame.iframeList.length;
for (i = 0; i < len; i++) {
if (frame.iframeList[i].source === eventObject.source) break;
}
frame.iframeList[i] = eventObject;
sameTab.iframeNameList[i] = eventObject.data.frameName;
if (!frame.convertAllLinks) return;
frame.sendIframeList(null);
break;
}
}
};
frame.hostname = frame.getHostname();
if (frame.hostname) {
window.addEventListener("message", frame.windowMessages, false);
chrome.storage.local.get(null, frame.checkLists);
}
} else {
// Iframes
frame = {
// Accept messages from the top window only.
windowMessages: function(eventObject) {
if (eventObject.source !== top) return;
if (!eventObject.data ||
eventObject.data.senderId !== "sameTabExtensionTop" ||
eventObject.data.message !== "nameList" ||
!eventObject.data.iframeNameList) return;
sameTab.iframeNameList = eventObject.data.iframeNameList;
sameTab.index = eventObject.data.index;
if (sameTab.converted) return;
sameTab.convertDocument(null);
},
// Tell top window that the window has unloaded
windowUnload: function(eventObject) {
var origin;
try {
origin = top.location.origin;
} catch(err) {
origin = "*";
}
top.postMessage({
senderId: "sameTabExtensionIframe",
message: "windowUnloaded",
}, origin);
},
// Post the window's name to the top window.
contentLoaded: function(eventObject) {
var origin;
try {
origin = top.location.origin;
} catch(err) {
origin = "*";
}
top.postMessage({
senderId: "sameTabExtensionIframe",
message: "contentLoaded",
frameName: window.name
}, origin);
}
};
window.onunload = frame.windowUnload;
window.addEventListener("message", frame.windowMessages, false);
document.addEventListener("DOMContentLoaded", frame.contentLoaded, false);
}
}());
Simply add the _top attribute on all forms below (function() {
var submitButtons = document.getElementsByTagName("button");
for (var i = 0; i < submitButtons .length; i++) {
submitButtons[i].setAttribute("target", "_top");
}
You can try setting the querySelectorAll to look for forms as well. I'm pretty sure that forms also support target.

Categories