📌  相关文章
📜  HTML<script> integrity Attribute(1)

📅  最后修改于: 2023-12-03 15:31:18.325000             🧑  作者: Mango

HTML integrity Attribute

The integrity attribute is used to ensure that the external resource being referred to in the document hasn't been tampered with. It is used with the <script> and <link> elements, and its main purpose is to provide security.

Syntax

The integrity attribute is added to the <script> and <link> elements, and it has the following syntax:

<script src="example.js" integrity="sha384-nC34ecH9CJLzBxR5OXJSv8H3uoCsaj7H/95t+y9iqTCNW3b4yUDoLX2nj8tgEUTO" crossorigin></script>

The integrity attribute value consists of two parts:

  • A hash algorithm that is used to hash the content of the external resource (e.g. sha384).
  • A hash that represents the content of the external resource that is being referred to.
How it works

When the browser loads the external resource, it calculates its hash and compares it with the hash that is specified in the integrity attribute. If the two hashes match, the external resource is considered to be authentic, and the browser executes it. Otherwise, it is rejected.

Benefits

The integrity attribute provides several benefits:

  • It helps protect against malicious attacks such as XSS (Cross-Site Scripting) and Man-in-the-middle attacks, by ensuring that the external resource hasn't been tampered with.
  • It helps ensure that the external resource is loaded correctly, by preventing any unexpected modifications.
  • It provides peace of mind for developers and users alike, by making sure that the external resource is authentic.
Conclusion

The integrity attribute is a valuable addition to the HTML specification that provides an additional layer of security and peace of mind for developers and users alike. By including this attribute in your <script> and <link> elements, you can help ensure the authenticity and integrity of your external resources.