New rule: Prevent/warn about the usage of window in favor of self.
See original GitHub issuePlease describe what the rule should do:
Prevent/warn about the usage of window
in favor of self
, with self
being a proxy to the current global context and should work across all environments in the browser.
What category of rule is this? (place an “X” next to just one item)
[ ] Enforces code style [x] Warns about a potential error [x] Suggests an alternate way of doing something [x] Other (please specify:)
- Enforces portability across non DOM environments
Provide 2-3 code examples that this rule will warn about:
// should warn/error on use of window and suggest usage of self instead
if (window.crypto && window.crypto.getRandomValues) {
// Modern browsers
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
window.crypto.getRandomValues(arr);
return arr;
};
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
// IE
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
window.msCrypto.getRandomValues(arr);
return arr;
};
} else {
// Old junk
Rand.prototype._rand = function() {
throw new Error('Not implemented yet');
};
}
===============
// should not warn/error on the usage of self
if (self.crypto && self.crypto.getRandomValues) {
// Modern browsers
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.crypto.getRandomValues(arr);
return arr;
};
} else if (self.msCrypto && self.msCrypto.getRandomValues) {
// IE
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.msCrypto.getRandomValues(arr);
return arr;
};
} else {
// Old junk
Rand.prototype._rand = function() {
throw new Error('Not implemented yet');
};
}
Why should this rule be included in ESLint (instead of a plugin)?
There is a large surface of non DOM related APIs being added to browsers that work across DOM and non DOM (WebWorker/ServiceWorker) environments. In many cases window
is used as a reference to the global context to test for the presence of those features which makes it non-portable across non DOM environments. As we move towards browsers with more and more capabilities beyond the DOM, this is going to become more of a problem. An eslint rule should alleviate the transition and enforce a very important best practice, having it as a plugin would mean less penetration and adoption across the board.
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
@dryajov Haha, that’s my mistake then, I thought you had already edited the issue. Sorry about that!
@platinumazure , I think there is no confusion, im going to enhance
no-restricted-globals
to take a custom message for globals, which is what has been suggested. I just haven’t gotten around changing this issue, will try to get to it today. 😃