Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Javascript in Chrome Extension -> Basic?

I get the feeling I'm missing something very obvious, but I've been looking everywhere and can't seem to make this work. In short, I want to turn a small Javascript script into a chrome extension to make it easier to use.

The script just reads text from a textArea, modifies the script and outputs it into a div. It works perfectly with any browser when running standalone, but doesn't seem to want to work when ran as a Chrome extension

Here are the files (I'm basically trying to convert the example):

Thanks!

manifest.json

    {
  "manifest_version": 2,

  "name": "One-click Kittens",
  "description": "This extension demonstrates a 'browser action' with kittens.",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "https://secure.flickr.com/"
  ]
}

popup.html

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width: 357px;
        overflow-x: hidden;
      }

      img {
        margin: 5px;
        border: 2px solid black;
        vertical-align: middle;
        width: 75px;
        height: 75px;
      }
    </style>

    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: http://developer.chrome.com/extensions/contentSecurityPolicy.html
     -->
    <script src="popup.js"></script>
  </head>
  <body>

    <textarea id="source">Text Entry.</textarea>
    <button onclick="main()" id="buttons">Generate</button>

    <div id="result">       
    </div>

  </body>
</html>

popup.js

function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}
like image 511
Albert Avatar asked Dec 25 '22 19:12

Albert


1 Answers

According to chrome extension documentation,

Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).

Read: http://developer.chrome.com/extensions/contentSecurityPolicy.html#JSExecution

Use in popup.js as

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', main);      
});
function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}
like image 60
Tamil Selvan C Avatar answered Dec 28 '22 08:12

Tamil Selvan C