JS Bookmarklets: Increase/decrease site's font size - javascript

I was using the code from here to enlargen sites:
var p=document.getElementsByTagName('*');
for(i=0;i<p.length;i++) {
if(p[i].style.fontSize){
var s=parseInt(p[i].style.fontSize.replace("px",""));
}
else {
var s=12;
}
s+=2;
p[i].style.fontSize=s+"px"
But this has recently stopped working on my Chrome (Version 81.0.4044.138 (Official Build) (64-bit)). I am curious as to why, and any working alternatives.
ٍٍExplaining "stopped working": After using it, the page goes blank, and sometimes shows "14px":

This article from 2ality says
Finish with undefined: If you don’t return (or finish with!) undefined, the result replaces the current web page. [Note: Webkit browsers such as Chrome and Safari never replace a page, only non-Webkit browsers such as Firefox do.]
but Chrome has changed this behavior.
Chrome now runs a code like
if (typeof bookmark_reslt === "string") {
document.body.innerHTML = bookmark_reslt
}
A minimal reproducible example of the bookmarklet is javascript: "14px"
The easiest solution is to add undefined in the end of the script.
Firefox executes a code like document.body.innerHTML = String(bookmark_reslt)
// examples to see how `toString` affects Bookmarklets in Firefox
javascript: a = {}; a; // <body>[object Object]</body>
javascript: a = {}; a.toString = ()=> 2; a; // <body>2</body>

Related

IE doesn't recognise Javascript Class and breaks

I wrote some Javascript code that works perfectly in all major browsers. Of course I made sure that none of this would be executed by Internet Explorer by creating a function that figures out what browser the user is using.
Here's the problem however: Even if I told IE not to execute the code, the browser still reads all of my Javascript and since it finds something it doesn't recognise it stops running any other Javascript.
The only thing I could think of doing was creating a function that would return if the user is using IE, but that doesn't seem to work since I think the problem comes from IE initially parsing my script and not being able to understand modern JS syntax.
Here's a simplified version of my code:
class Section {
constructor(dom, startPosition, endPosition, backgroundPosition) {
this.dom = dom;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.backgroundPosition = backgroundPosition;
}
}
function isIE() {
ua = navigator.userAgent;
/* MSIE used to detect old browsers and Trident used to newer ones*/
var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
return is_ie;
}
let sections = [];
function sectionParallax() {
if (!isIE()) {
sections.push( new Section("test", 123, 123, 123))
}
}
IE's console reports:
SCRIPT1002: Syntax error
On class Section.
I'm completely out of ideas on what to do here. How do I make sure IE doesn't load this part of the code?
JavaScript classes and constructor not support IE browser, so, in the IE browser, it will show the "SCRIPT1002: Syntax error" error.
You could modify your code as below:
var Section = /** #class */ (function () {
function Section(dom, startPosition, endPosition, backgroundPosition) {
this.dom = dom;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.backgroundPosition = backgroundPosition;
}
return Section;
}());
function isIE() {
ua = navigator.userAgent;
/* MSIE used to detect old browsers and Trident used to newer ones*/
var is_ie = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
return is_ie;
}
var sections = [];
function sectionParallax() {
if (!isIE()) {
/*If not using IE browser. */
var newsection = new Section("test", 123, 123, 123);
sections.push(newsection);
}
}
The JS parser has to parse the JavaScript you tell it to load, even if it is a function that never executes.
If you want to stop IE from loading it, then don't load the <script> which contains it. This means you need to dynamically add the <script> if the browser does support the feature.
If you need to support IE, then don't deliver JS to the browser that uses syntax IE doesn't recognise. Consider using a tool like Babel to transpile it to an older version of JavaScript which IE does support.
You could check for IE before loading the script with a Conditional Comment :
<!--[if !IE]>-->
<script src="script.js"></script>
<!--<![endif]-->

Detect if console/devtools is open in all browsers

I'm trying to create a script which will run when any browser console is opened or closed. Is there any way to detect if the browser console in all browsers (Firefox/IE/Chrome/Safari/Opera) is open or not via JavaScript, jQuery, or any other client-side script?
If you are willing to accept an interference for the user,
you could use the debugger statement, as it is available in all major browsers.
Side note: If the users of your app are interested in console usage, they're probably familiar with dev tools, and will not be surprised by it showing up.
In short, the statement is acting as a breakpoint, and will affect the UI only if the browser's development tools is on.
Here's an example test:
<body>
<p>Devtools is <span id='test'>off</span></p>
<script>
var minimalUserResponseInMiliseconds = 100;
var before = new Date().getTime();
debugger;
var after = new Date().getTime();
if (after - before > minimalUserResponseInMiliseconds) { // user had to resume the script manually via opened dev tools
document.getElementById('test').innerHTML = 'on';
}
</script>
</body>
devtools-detect should do the job. Try the simple demo page.
devtools-detect → detect whether DevTools is open, and its orientation.
Supported Browsers:
DevTools in Chrome, Safari, Firefox & Opera
Caveats:
Doesn't work if DevTools is undocked (separate window), and may show a false positive if you toggle any kind of sidebar.
I don't think it is directly possible in JS for security reasons.But in here
they are claiming that it is possible and is useful for when you want something special to happen when DevTools is open. Like pausing canvas, adding style debug info, etc.
But As #James Hill tell in this, I also thinks even if a browser chose to make this information accessible to the client, it would not be a standard implementation (supported across multiple browsers).
Also can also try this one also here.
It's not possible in any official cross browser way, but if the occasional false positive is acceptable, you can check for a window.onresize event. Users resizing their windows after loading a page is somewhat uncommon. It's even more effective if you expect users will be frequently opening the console, meaning less false positives as a percentage.
window.onresize = function(){
if ((window.outerHeight - window.innerHeight) > 100) {
// console was opened (or screen was resized)
}
}
Credit to https://stackoverflow.com/a/7809413/3774582. Although that question is chrome specific, the concept applies here.
To expand on this, if you need a very low tolerance on false positives, most window resizes will trigger this event dozens of times because it is usually done as a drag action, while opening the console will only trigger this once. If you can detect this, the approach will become even more accurate.
Note: This will fail to detect if the console is already open when the user visits the page, or if the user opens the console in a new window.
(function() {
'use strict';
const el = new Image();
let consoleIsOpen = false;
let consoleOpened = false;
Object.defineProperty(el, 'id', {
get: () => {
consoleIsOpen = true;
}
});
const verify = () => {
console.dir(el);
if (consoleIsOpen === false && consoleOpened === true) {
// console closed
window.dispatchEvent(new Event('devtools-opened'));
consoleOpened = false;
} else if (consoleIsOpen === true && consoleOpened === false) {
// console opened
window.dispatchEvent(new Event('devtools-closed'));
consoleOpened = true;
}
consoleIsOpen = false;
setTimeout(verify, 1000);
}
verify();
})();
window.addEventListener('devtools-opened', ()=>{console.log('opened')});
window.addEventListener('devtools-closed', ()=>{console.log('closed')});
Here is a code that worked for me.
This solution works like a charm
https://github.com/sindresorhus/devtools-detect
if you are not using modules - disable lines
// if (typeof module !== 'undefined' && module.exports) {
// module.exports = devtools;
// } else {
window.devtools = devtools;
// }
and result is then here
window.devtools.isOpen
I for my project use the blur event.
function yourFunction() {}
window.addEventListener('blur',(e)=>{e.preventDefault(); yourFunction()})
This will execute yourFunction when the window loses focus.
For instance when someone opens the DevTools.
Okay seems like it also fires when you try to access a different window... so maybe not the best solution.
Maybe pair it with looking at the width of the browser.
If it chainged you can be pretty sure about it I think

setInterval Breaks Page To Be Shown

I have that line of code:
var checkExist5 = setInterval(function() {
if (lock == 5 && $("#id1").length && $("#id2").length) {
console.log("debug");
clearInterval(checkExist5);
lock = -1;
}
}, 100);
it works at Firefox but it breaks the page at Internet Explorer. It does not give any error at console but the page is not shown (ie 9). What may be the reason?
I found the reason. It was because of
console.log("debug");
It was not working at Internet Explorer 9. There is an explanation here: Does IE9 support console.log, and is it a real function?

Override Ctrl+M hotkey of Facebook in Firefox

I'm working on a bookmarklet which will let users to write on any input fields in our language. We choose Ctrl+M for switching layout between default and our language (Inspired by Wikipedia). It was working fine in almost every website with chrome. When we started checking with Firefox we found that it only fails in Facebook.
Moreover, Facebook catches the Ctrl+M from outside the window
scope. Like, form the address bar, search bar, firebug console, etc.
I've tried with raw javascript, jQuery and also with the jQuery Hotkeys plugin by John Resig but no luck :(
Here is a version that I had tried. You can run it on your Firebug console for testing purpose -
(function(){
var noConflictMode = false;
if(typeof $ !== 'undefined') noConflictMode = true;
if(typeof jQuery === 'undefined') {
var root = (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]);
var ns = document.createElementNS && document.documentElement.namespaceURI;
var script = ns ? document.createElementNS(ns, 'script') : document.createElement('script');
script.type = 'text/javascript';
script.onreadystatechange = function () {
if (this.readyState == 'complete') test();
}
script.onload= test;
script.src= 'https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js';
root.appendChild(script);
} else {
test();
}
function test() {
if(noConflictMode) jQuery.noConflict();
jQuery(window).on('keydown keyup keypress', function(e){
e.preventDefault();
// For Firefox
e.stopPropagation();
// Extra effort :|
e.stopImmediatePropagation()
e.cancelBubble = true;
console.log(e);
return false;
});
}
})();
You can NOT do that on client-side web for security reasons, you can code anything in JS or JQ or any language you want but MOZ never will take care of your code.
Take care, one thing is that the browser "compile" your code and work with it, and another thing is that you can change the browser itself. For that reasons there's the "add-on".
For example, you can't change the kernel of Visual Studio programming in V.S. :D
BUT...
... you can ask to the user re-bind the keys, you have 3 ways to do that:
1) installing a MOZ add-on (or your own addon)
2) Working with: http://mxr.mozilla.org/seamonkey/source/dom/public/idl/events/nsIDOMKeyEvent.idl
3) installing a shortcut keyb at OS level with higher priority than the App (in this case, MOZ) (you can do it with C#). Alt+tab combination is an example of high level shortcut, or "Prnt Scrn"
There is NO way to do that with about:config, neither.
Maybe this url can help you, but i suggest you try asking for changes in MOZ and not asking for Javascript code.
http://www-archive.mozilla.org/unix/customizing.html#keys

Why would this code work in IE and fail in Firefox and Chrome?

So loading up our new web application in Firefox and Chrome I had an alert subtly tell me that a tabStrip couldn't be found. Following through the code I found this function:
function initializeTabStrip() {
var tblList = document.getElementsByTagName("table");
var tabStrip = null;
for (var i = 0; i < tblList.length; ++i) {
if (typeof (tblList[i].tabStripRoot) != "undefined") {
tabStrip = tblList[i];
break;
}
}
if (tabStrip) {
window.tabStrip = new TabStrip(tabStrip);
}
else {
alert("couldn't find tabstrip");
}
}
In both Firefox and Chrome, typeof (tblList[i].tabStripRoot) comes up to be undefined, whereas in Internet Explorer the same section of code will find an item, and follow through correctly.
I've tried using Firebug and IE's developer toolbar script debugging tool to follow through and attempt to discover what 'tabStripRoot' is, but I haven't had any luck.
Would any of you JavaScript guru's be able to give me some direction into why one out of three browsers works?
Thanks for your help.
You're relying on IE's non-standard ability to access arbitrary attributes as properties of DOM elements.
In standards-compliant browsers, you cannot write someElement.tabStripRoot to access the tabStripRoot attribute.
Change it to tblList[i].getAttribute('tabStripRoot').

Categories