Resolving "Refused to Load Script" Issue in Android Lollipop and Above
When deploying apps to Android devices with Lollipop or higher, users may encounter the error: "Refused to load the script because it violates the following Content Security Policy directive." This issue arises due to stricter content security policies implemented in these versions.
Understanding the Content Security Policy
The Content Security Policy (CSP) is a security measure that restricts the loading of external resources on a web page. It helps prevent malicious content from being executed. By specifying a set of allowed domains, the policy defines which scripts, styles, and images can be loaded.
Default Policy for KitKat and Before
On Android KitKat and earlier, the default CSP is:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
This policy allows scripts from the origin of the site ('self') and from a few specific domains, including Google Analytics ('https://ssl.gstatic.com').
Restricted Policy in Lollipop and Above
In Android Lollipop and above, the default CSP becomes more restrictive:
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-eval' 'unsafe-inline'; object-src 'self'; style-src 'self' 'unsafe-inline'; media-src *">
This policy only allows scripts from the origin of the site and doesn't allow loading scripts from external sources.
Resolution
To resolve the issue, you need to modify the CSP to allow scripts from the desired domain. In this case, you want to load a script from "http://Guess.What.com/MyScript.js."
Corrected CSP
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; script-src 'self' http://Guess.What.com 'unsafe-inline' 'unsafe-eval'; ">
By adding the line "script-src 'self' http://Guess.What.com 'unsafe-inline' 'unsafe-eval';" to the CSP, you are explicitly allowing scripts from that domain.
After implementing the corrected CSP, the script can be loaded successfully without any errors.
The above is the detailed content of How to Fix \'Refused to Load Script\' Error in Android Lollipop and Above?. For more information, please follow other related articles on the PHP Chinese website!