Skip to content

Commit

Permalink
Update: check template literal in no-script-url (#13775)
Browse files Browse the repository at this point in the history
* Fix: check template literal in no-script-url

* handle uppercase

* handle tagged template literal

* change to toLowerCase

* check only string literal
  • Loading branch information
yeonjuan committed Oct 23, 2020
1 parent bfe97d2 commit 5183b14
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 8 deletions.
2 changes: 2 additions & 0 deletions docs/rules/no-script-url.md
Expand Up @@ -10,6 +10,8 @@ Examples of **incorrect** code for this rule:
/*eslint no-script-url: "error"*/

location.href = "javascript:void(0)";

location.href = `javascript:void(0)`;
```

## Compatibility
Expand Down
28 changes: 21 additions & 7 deletions lib/rules/no-script-url.js
Expand Up @@ -7,6 +7,8 @@

"use strict";

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand All @@ -31,18 +33,30 @@ module.exports = {

create(context) {

/**
* Check whether a node's static value starts with "javascript:" or not.
* And report an error for unexpected script URL.
* @param {ASTNode} node node to check
* @returns {void}
*/
function check(node) {
const value = astUtils.getStaticStringValue(node);

if (typeof value === "string" && value.toLowerCase().indexOf("javascript:") === 0) {
context.report({ node, messageId: "unexpectedScriptURL" });
}
}
return {

Literal(node) {
if (node.value && typeof node.value === "string") {
const value = node.value.toLowerCase();

if (value.indexOf("javascript:") === 0) {
context.report({ node, messageId: "unexpectedScriptURL" });
}
check(node);
}
},
TemplateLiteral(node) {
if (!(node.parent && node.parent.type === "TaggedTemplateExpression")) {
check(node);
}
}
};

}
};
28 changes: 27 additions & 1 deletion tests/lib/rules/no-script-url.js
Expand Up @@ -22,7 +22,19 @@ ruleTester.run("no-script-url", rule, {
valid: [
"var a = 'Hello World!';",
"var a = 10;",
"var url = 'xjavascript:'"
"var url = 'xjavascript:'",
{
code: "var url = `xjavascript:`",
parserOptions: { ecmaVersion: 6 }
},
{
code: "var url = `${foo}javascript:`",
parserOptions: { ecmaVersion: 6 }
},
{
code: "var a = foo`javaScript:`;",
parserOptions: { ecmaVersion: 6 }
}
],
invalid: [
{
Expand All @@ -36,6 +48,20 @@ ruleTester.run("no-script-url", rule, {
errors: [
{ messageId: "unexpectedScriptURL", type: "Literal" }
]
},
{
code: "var a = `javascript:`;",
parserOptions: { ecmaVersion: 6 },
errors: [
{ messageId: "unexpectedScriptURL", type: "TemplateLiteral" }
]
},
{
code: "var a = `JavaScript:`;",
parserOptions: { ecmaVersion: 6 },
errors: [
{ messageId: "unexpectedScriptURL", type: "TemplateLiteral" }
]
}
]
});

0 comments on commit 5183b14

Please sign in to comment.