The script tag introduces the file

In HTML, the script tag can import a JS file via the SRC attribute. The imported JS file can be local or remote.

1. Import local files

Development environments generally introduce native JS files.

<script src="./js/index.js"></script>
Copy the code

2. Import remote files

After being deployed online, it is generally distributed to the CDN. Remote files need to be imported, such as:

<script src="https://cdn.xxx.xx/js/index.js"></script>
Copy the code

There is only one problem with introducing remote files, and if the corresponding files are tampered with, the user may be affected. Although CDN is generally reliable, but can not exclude the attack by hackers.

In this case, security verification can be done through the integrity property of the Script tag.

Integrity Security Verification

The integrity property configures the hash value of the JS file. When the browser downloads the JS file, it hashes the FILE. If the file is consistent, the file is loaded normally.

Like:

<script
	integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
	src="https://cdn.xxx.xx/js/index.js"></script>
Copy the code

Let’s look at an example.

1. Import CDN resources of the VUE

For example, we want to introduce CDN resources of VUE:

https://unpkg.com/[email protected]/dist/vue.global.js
Copy the code

You can use www.srihash.org/ to generate hash values.

Finally, add the integrity value to the script tag.

<script src="https://unpkg.com/[email protected]/dist/vue.global.js"
	integrity="sha384-0k9//QJdpmfSdp5IK3oJjOYPfz42f2FE0goMLtK9Vq7aKllvc4Lnz7lHPHiFhvDP" 
	crossorigin="anonymous">
</script>
Copy the code

2. Check whether the alarm is normal

If the integrity value is changed, the browser will report the following error:

Failed to find a valid digest in the 'integrity' attribute for resource 'https://unpkg.com/[email protected]/dist/vue.global.js'  with computed SHA-256 integrity 'Wr5PnkpmZ3oQFRZLfDrI6fsePSMak5h8rW2rqq+mdWg='. The resource has been blocked.Copy the code

The hash value of the CDN file does not match integrity.

The resources

Subresource Integrity:developer.mozilla.org/zh-CN/docs/…