jsx-no-script-url

Try in Playground
react-best-practicesBest PracticeWarning

0

No tags

No CWE or CVE

This rule will log a warning whenever a href or to prop starts with javascript:.

React considers this pattern as a dangerous attack surface.

In React 16.9, for any URLs starting with javascript: they will log a warning. In future major releases, React will throw an error if it encounters a javascript: URL.

View a similar rule from ESLint, react/jsx-no-script-url.

Ast Rule: html element


jsx-no-script-url

How to write a rule
const LINK_PROPS = ['href', 'to']

function getStringValue(value) {
  return value?.replace(/^\"/g, "").replace(/\"$/g, "") || ""
}

function getPropStringValue(value) {
  if (value.elements) {
    return getStringValue(value?.elements[0]?.value)
  } else {
    return getStringValue(value?.value)
  }
}

function visit(node, filename, code) {
  if (!node || !node.tag) return;

  if (node.attributes.length === 0) return;

  const linkProp = node.attributes.find(attribute => LINK_PROPS.includes(attribute.name?.value))

  if (getPropStringValue(linkProp.value).replace(/\"$/g, "").startsWith("javascript:")) {
    const error = buildError(
      linkProp.start.line,
      linkProp.start.col,
      linkProp.end.line,
      linkProp.end.col,
      `Disallow usage of "javascript:" URLs`,
      "WARNING",
      "BEST_PRACTICE"
    )
    addError(error)
  }
}

valid.jsx

Expected test result: no error

<Link to="/home"></Link>
<Foo href="https://www.google.com"></Foo>
<Foo to="edit"></Foo>

invalid.jsx

Expected test result: has error

<Foo href="javascript:"></Foo>
<a href={"javascript:"}></a>
<Link to="javascript:void(0)"></Link>
<Foo href="javascript:void(0)"></Foo>
<Foo to="javascript:void(0)"></Foo>
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.