初学PhoneGap,今天鼓捣了一天终于把环境以及如何创建项目搞明白了。首先说说我遇到的问题,我已经通过命令行创建好项目,并且手动加了该用的插件。随后我按照书里介绍的开开心心的敲了如下代码:
<script type="text/javascript"> document.addEventListener("deviceready", onDeviceReady, true); function onDeviceReady() { console.log("******phonegap*****"); navigator.notification.alert("PhoneGap is working", function(){}, "", ""); } </script>
随后我编译项目,打开xcode,运行项目,满怀期待的想看一下效果。结果,xcode中console无任何信息,alert也没弹出。
这让我很费解,什么原因呢?找了好久,终于找到了原因。
大家打开index页面时,不知有没有注意到这样一段注释:
<!-- Customize this policy to fit your own app‘s needs. For more guidance, see: https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy Some notes: * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this: * Enable inline JS: add ‘unsafe-inline‘ to default-src -->
OK,这就是我上面问题的原因。原因是通过命令行生成的项目中,index页面中自动加入了如下代码段:
<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 *">
这段代码默认禁用了行内javascript,所以导致我上面的问题,解决方法是在default-src中加入‘unsafe-inline‘:
<meta http-equiv="Content-Security-Policy" content="default-src ‘self‘ ‘unsafe-inline‘ data: gap: https://ssl.gstatic.com ‘unsafe-eval‘; style-src ‘self‘ ‘unsafe-inline‘; media-src *">
关于更多CSP资料可以参考:
http://www.2cto.com/Article/201408/327064.html
时间: 2024-10-20 12:12:19