0

I'm coding the simplest Chrome extension using HTML and JavaScript, but apparently JavaScript is not working, and I don't know why. Here is the my HTML code:

<script>
    function myFunction()
    {
    alert("I am an alert box!");
    }
  </script>
  <input type="button" onclick="myFunction()" value="Show alert box">

and here is my manifest.json file code :

{
  "name": "Blank new tab page",
  "version": "0.2",
  "incognito": "split",
  "chrome_url_overrides": {
    "newtab": "blank.html"
  },
  "manifest_version": 2
}
Fabrício Matté
  • 65,581
  • 23
  • 120
  • 159
Ryzal Yusoff
  • 867
  • 1
  • 16
  • 42
  • 1
    Inline JS is not allowed in popup pages. And IMHO it is a good thing, not only for security as Chrome claims, but also forces people to separate structure from behavior. – Fabrício Matté Jun 28 '13 at 02:04
  • The duplicate question has an answer that will solve the issue. Be sure to search first! :) – Chris Baker Jun 28 '13 at 02:06

1 Answers1

0

Is your HTML DOCTYPE transitional? If not, maybe your code should look more like:

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<body>
  <input type='button' value='Show alert box' onclick='myFunction()' />
  <script type='text/javascript'>
    function myFunction(){
      alert('I am an alert box!');
    }
  </script>
</body>
</html>

Of course, I rearranged it. Your code should work though. I personally would recommend that your code look more like:

<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'
  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<body>
  <input type='button' value='Show alert box' id='btn' />
  <script type='text/javascript' src='external.js'></script>
  <script type='text/javascript'>
    showAlert('btn');
  </script>
</body>
</html>

external.js will be cached. It can look something like:

function E(e){
  return document.getElementById(e);
}
function showAlert(e){
  E(e).onclick = function(){
    alert('I am an alert box!');
  }
}

The latter code is more reusable, and will give you an idea about jQuery's $(). It's a way more sophisticated version of my E() function.

StackSlave
  • 10,198
  • 2
  • 15
  • 30