在Chrome扩展中运行Javascript-> Basic

Run Javascript in Chrome Extension -> Basic?

本文关键字:Basic Javascript- 运行 Chrome 扩展      更新时间:2023-09-26

我感觉我错过了一些非常明显的东西,但我一直在到处寻找,似乎无法完成这项工作。简而言之,我想将一个小的Javascript脚本变成chrome扩展,以使其更易于使用。

该脚本只是从文本区域中读取文本,修改脚本并将其输出到div 中。独立运行时,它与任何浏览器完美配合,但在作为Chrome扩展程序运行时似乎不想工作

以下是文件(我基本上是在尝试转换示例(:

谢谢!

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/"
  ]
}

弹出窗口.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>

弹出窗口.js

function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}

根据 chrome 扩展程序文档,

内联 JavaScript 不会被执行。此限制禁止内联<script>块和内联事件处理程序(例如 <button onclick="..."> (。

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

在弹出窗口中使用.js作为

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', main);      
});
function main() {
    var source = document.getElementById('source').value;
    document.getElementById("result").innerHTML = source;
}