Skip to content

Commit

Permalink
Add browser checkings (#9)
Browse files Browse the repository at this point in the history
* Check if we are in a browser or not

* Update minor version
  • Loading branch information
calvellido committed Feb 5, 2020
1 parent ddbd906 commit 20f4e65
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 30 deletions.
75 changes: 46 additions & 29 deletions index.js
@@ -1,34 +1,51 @@
// focus - focusOptions - preventScroll polyfill
var supportsPreventScrollOption = false;
try {
var focusElem = document.createElement('div');
focusElem.addEventListener('focus', function(event) {
event.preventDefault();
event.stopPropagation();
}, true);
focusElem.focus(
Object.defineProperty({}, 'preventScroll', { get: function () {
supportsPreventScrollOption = true;
}})
);
} catch(e) {}

if (HTMLElement.prototype.nativeFocus === undefined && !supportsPreventScrollOption) {
(function() {
if (
typeof window === "undefined" ||
typeof document === "undefined" ||
typeof HTMLElement === "undefined"
) {
return;
}

HTMLElement.prototype.nativeFocus = HTMLElement.prototype.focus;
var supportsPreventScrollOption = false;
try {
var focusElem = document.createElement("div");
focusElem.addEventListener(
"focus",
function(event) {
event.preventDefault();
event.stopPropagation();
},
true
);
focusElem.focus(
Object.defineProperty({}, "preventScroll", {
get: function() {
supportsPreventScrollOption = true;
}
})
);
} catch (e) {}

var patchedFocus = function (args) {
var actualPosition = window.scrollY || window.pageYOffset;
this.nativeFocus();
if (args && args.preventScroll) {
// Hijacking the event loop order, since the focus() will trigger
// internally an scroll that goes to the event loop
setTimeout(function() {
window.scroll((window.scrollX || window.pageXOffset), actualPosition);
}, 0);
}
}
if (
HTMLElement.prototype.nativeFocus === undefined &&
!supportsPreventScrollOption
) {
HTMLElement.prototype.nativeFocus = HTMLElement.prototype.focus;

HTMLElement.prototype.focus = patchedFocus;
var patchedFocus = function(args) {
var actualPosition = window.scrollY || window.pageYOffset;
this.nativeFocus();
if (args && args.preventScroll) {
// Hijacking the event loop order, since the focus() will trigger
// internally an scroll that goes to the event loop
setTimeout(function() {
window.scroll(window.scrollX || window.pageXOffset, actualPosition);
}, 0);
}
};

}
HTMLElement.prototype.focus = patchedFocus;
}
})();
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "focus-options-polyfill",
"version": "1.1.1",
"version": "1.2.0",
"description": "JavaScript polyfill for the WHATWG spec of focusOptions, that enables a set of options to be passed to the focus method.",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 20f4e65

Please sign in to comment.