UNPKG

next-csrf

Version:

CSRF mitigation library for Next.js

62 lines (52 loc) 2.3 kB
/* Clicking on a link that has a focusable element in its ancestry [tabindex="-1"], can lead to that parental element gaining focus, instead of the link. Example: <div tabindex="-1"> <a href="#foo">click me</a> </div> This (wrong) behavior was observed in Chrome 38, iOS8, Safari 6.2, WebKit r175131 It is not a problem in Firefox 33, Internet Explorer 11, Chrome 39. */ import getFocusTarget from '../get/focus-target'; import isValidTabIndex from '../is/valid-tabindex'; import decorateContext from '../util/decorate-context'; import platform from '../util/platform'; var engage = void 0; var disengage = void 0; // This fix is only relevant to WebKit var relevantToCurrentBrowser = platform.is.WEBKIT; if (!relevantToCurrentBrowser) { engage = function engage() {}; } else { (function () { // add [tabindex="0"] to the (focusable) element that is about to be clicked // if it does not already have an explicit tabindex (attribute). // By applying an explicit tabindex, WebKit will not go look for // the first valid tabindex in the element's parents. var handleBeforeFocusEvent = function handleBeforeFocusEvent(event) { // find the element that would receive focus var target = getFocusTarget({ context: event.target }); if (!target || target.hasAttribute('tabindex') && isValidTabIndex(target)) { // there's nothing to focus, or the element already has tabindex, we're good return; } // assign explicit tabindex, as implicit tabindex is the problem target.setAttribute('tabindex', 0); // add cleanup to the RunLoop (window.setImmediate || window.setTimeout)(function () { target.removeAttribute('tabindex'); }, 0); }; engage = function engage(element) { element.addEventListener('mousedown', handleBeforeFocusEvent, true); element.addEventListener('touchstart', handleBeforeFocusEvent, true); }; disengage = function disengage(element) { element.removeEventListener('mousedown', handleBeforeFocusEvent, true); element.removeEventListener('touchstart', handleBeforeFocusEvent, true); }; })(); } export default decorateContext({ engage: engage, disengage: disengage }); //# sourceMappingURL=pointer-focus-parent.js.map