2

I'm trying to make a google chrome extension that displays the date when you open a new tab. However, my code simply isn't executing the javascript code. I know the code outside the portion works because I tested it by having it show "new tab opened" when I open a new tab. It's just not showing the date. Any help would be much appreciated :)

<!DOCTYPE html>
<html>
<body bgcolor="C1E9E1" onload="displayDate();">
    <div>new tab opened</div>
    <p id="data"></p>
    <script type ="text/javascript">
        function displayDate(){
            var day =  new Date();
            var y = day.getFullYear().toString().substr(-2);
            var m = day.getMonth() + 1;
            var d = day.getDate();
            if(m < 10){
                m = "0"+m
                }
            if(d < 10){
                d = "0"+d
                }
            var dateFormat = m + " " + d + " " + y
            document.getElementById("data").innerHTML = dateFormat;
            } 
    </script>
</body>

xerop
  • 67
  • 1
  • 1
  • 7
  • 1
    maybe the onload isn't executing, have you tried adding `displayDate()` after the function inside the script tag? – IrkenInvader Jan 31 '18 at 00:22
  • Have you tried using an [IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression)? – mhodges Jan 31 '18 at 00:24

1 Answers1

1

Do not use inline scripts with chrome extensions. You need to source the script from a separate js file.

Example: <script src="myscript.js">

Should work after this, or at least allow you to debug properly. It may work for very minimal logic, but certainly encounter issues further along.

And in your manifest.json include the content_scripts item.

"content_scripts": [
    {
      "css": ["mystyles.css"],
      "js": ["myscript.js"]
    }
  ]

Refer to this issue for similar resolution: Chrome 18+: How to allow inline scripting with a Content Security Policy?

Nicholas Porter
  • 2,588
  • 2
  • 23
  • 37
  • Refer to this issue for similar resolution: https://stackoverflow.com/questions/8502307/chrome-18-how-to-allow-inline-scripting-with-a-content-security-policy – Nicholas Porter Jan 31 '18 at 00:33
  • Thanks! This made it a lot easier to debug. My problem now is that I put multiple functions (each function returns either date or time) in the same script and I'm having trouble calling that specific function in html. I've been looking it up everywhere and I can't find anything that works. Do you have any ideas? Thanks again! – xerop Feb 01 '18 at 02:03
  • @xerop A couple things you can try: 1.) put your ` – Nicholas Porter Feb 01 '18 at 05:38