0

I am working with a chrome app and I developed it as a normal web page. It includes several .js files and also calls some functions on click and on load.

<body onload="thisIsOnLoadFunction()">

<button class='btn btn-info btn-large icon-undo pull-right' onclick='cancelAll()'>

They are some of them. But it does not work as normally when I run it as an app.

in console it shows an error saying

 Refused to execute inline event handler because it violates the following
 Content Security Policy directive: "default-src 'self' 
 chrome-extension-resource:".
 Note that 'script-src' was not explicitly set,
 so 'default-src' is used as a fallback

How can I get that working.

bula
  • 8,719
  • 5
  • 27
  • 44
  • possible duplicate of [Content-Security-Policy error in google chrome extension making](http://stackoverflow.com/questions/11045653/content-security-policy-error-in-google-chrome-extension-making) – sowbug Mar 10 '14 at 21:51

1 Answers1

3

You can not use inline event handler in apps. It is a security issue.

Include a JS file where you do something like:

document.getElementById("some_id").addEventListener("click", some_function);

or use querySelector attach event directly by ..ById("some_id").onclick etc.

Typically wrap the code in:

document.addEventListener('DOMContentLoaded', function () {
  ....
});

As an extra note to adding event listeners.

If you need to pass arguments to a function there is various ways. One way is to use closures, another way which I find cleaner is to use bind. As this is for an app you do not need to vory about browser capabilities on bind.

Example:

function some_fun(i, e) {
    console.log(i); <-- This will be value of `i` in loop
    console.log(e); <-- This will be the event.
}

var p = document.getElementsByTagName('P'),
    i;

for (i = 0; i < p.length; ++i) {
    p[i].addEventListener("click", some_fun.bind(null, i));
}

Another very useful thing with bind() is the ability to pass context. For example:

function MyObj(x, y) {
    this.x = x;
    this.y = y;
}

var my_obj = new MyObj(42, 13);

someElem.addEventListener("click", my_fun.bind(my_obj));

When someElem now is clicked you can use things like this.x and get 42.

user13500
  • 3,817
  • 2
  • 26
  • 33