diff --git a/docs/rules/no-script-url.md b/docs/rules/no-script-url.md index 475959dacb1..5c71eb41327 100644 --- a/docs/rules/no-script-url.md +++ b/docs/rules/no-script-url.md @@ -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 diff --git a/lib/rules/no-script-url.js b/lib/rules/no-script-url.js index 2078fc1dcea..0c820524403 100644 --- a/lib/rules/no-script-url.js +++ b/lib/rules/no-script-url.js @@ -7,6 +7,8 @@ "use strict"; +const astUtils = require("./utils/ast-utils"); + //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ @@ -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); } } }; - } }; diff --git a/tests/lib/rules/no-script-url.js b/tests/lib/rules/no-script-url.js index 6eca268ce8d..8dd296161a8 100644 --- a/tests/lib/rules/no-script-url.js +++ b/tests/lib/rules/no-script-url.js @@ -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: [ { @@ -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" } + ] } ] });