Search code examples
javascriptcordovaevent-handlingphonegap

Cordova. Can't add event to button


I'm trying to make button do something using event listener in separate JS-script. I'm getting this error in browser (which refers to <body onload="onLoad()"> line): Refused to execute inline event handler because it violates the following Content Security Policy directive... This is my HTML:

<!DOCTYPE html>
<html>
    <head>
        <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 *; img-src 'self' data: content:;">
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <title>Test</title>
        <script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </head>
    <body onload="onLoad()">
    <div id="left_panel">
        <div class="btn" id="add" onclick="insert()">Add</div>
    </div>
    <div id="list">
    </div>
    </body>
</html>

JS-script:

function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
    document.addEventListener("resume", onResume, false);
    document.addEventListener("menubutton", onMenuKeyDown, false);
    document.getElementById("list").addEventListener("insert", insert, false);
}

function insert() {
    ...
}

function onPause() {}

function onResume() {}

function onMenuKeyDown() {}

Solution

  • The Message shows that your error is in the third line of your HTML document. There is your Content Security Policy, read the error carefully and add 'script-src' with the correct parameters to active the execution of javascript:

    script-src 'self' 'unsafe-inline' 'unsafe-eval'