We're All Mad Here
We're All Mad Here

Reputation: 1554

Trouble creating chrome extension

I have successfully created an chrome extension which simply when pressed says hello word. Now when i tried to demonstrate a simple button when pressed alert comes out, doesn't work. I am thinking if it is perhaps because i use javascript inside and it has html extension.

In my folder which gets loaded in chrome has inside a)manifest.json b)lab.html c)an icon

lab.html

<textarea id="s" rows="2" cols="4" name="p"></textarea></br>

<button onclick="button()">Submit</button>

<script>
function button()

{
   alert("alert");
}
</script>

manifest

{
    "name": "Your Extension Name",
    "description": "Your Extension Description", 
    "browser_action": {
        "default_icon": {
            "38": "icon.png"
            }, 
        "default_title": "Your Extension Popup Title", 
        "default_popup": "lab.html"
    }, 
    "manifest_version": 2,
    "update_url": "http://clients2.google.com/service/update2/crx",
    "content_security_policy": "script-src 'self' https://www.google.com; object-src 'self'",
    "version": "0.1"
}

Upvotes: 1

Views: 60

Answers (2)

abraham
abraham

Reputation: 47893

You can't execute inline JavaScript because of the Content Security Policy. The Chrome dev docs have additional details.

You basically have to pull the JavaScript into a different file.

// script.js

function button()
{
   alert("alert");
}

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

Upvotes: 2

frosty
frosty

Reputation: 21762

Try reformatting your javascript:

function button(){
    alert('alert');
}

And then let's call your function as soon as the page loads, just to make sure that it is working.

So do this:

function button(){
    alert('alert'); 
}
button(); //call it immediately

Let me know how it goes.

Upvotes: 1

Related Questions