學習PhoneGap過程遇到的問題1(csp致使行內console和alert失效)

初學PhoneGap,今天鼓搗了一天終於把環境以及如何建立項目搞明白了。首先說說我遇到的問題,我已經經過命令行建立好項目,而且手動加了該用的插件。隨後我按照書裏介紹的開開心心的敲了以下代碼:javascript

<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也沒彈出。html

這讓我很費解,什麼緣由呢?找了很久,終於找到了緣由。java

你們打開index頁面時,不知有沒有注意到這樣一段註釋:git

    <!--
    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頁面中自動加入了以下代碼段:github

<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':apache

 <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資料能夠參考:xcode

http://www.2cto.com/Article/201408/327064.htmlapp

相關文章
相關標籤/搜索