简体   繁体   中英

Loading JavaScript in a Chrome Extension

This is my first post on SO and my first time making a Chrome Extension. I've read alot of documentation, but I am still unsure how to get this to work. Below are my html and js files. I want to be able to type something in the source box and have the have the word print out in the results area in real time. I have tested this code on my local host so i know it works, but for some reason it is acting up as a chrome extension.

popup.html

<!doctype html>
<html>
<head>
<title>Getting Started Extension 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>

<script src="popup.js"></script>

</head>
<body>

<textarea id="source"></textarea>

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

</body>
</html>

Here's the js:

 function main() {
  document.getElementById('source').keydown(function() {
    var source = document.getElementById('source').value;
    var outputValue = source.replace(/command/gi, "⌘")
                            .replace(/tab/gi, "⇥")
                            .replace(/return/gi, "⏎")
                            .replace(/option/gi, "⌥")
                            .replace(/control/gi, "⌃")
                            .replace(/esc/gi, "⎋")
                            .replace(/left/gi, "←")
                            .replace(/down/gi, "↓")
                            .replace(/up/gi, "↑")
                            .replace(/right/gi, "→")
                            .replace(/shift/gi, "⇧")
                            .replace(/eject/gi, "⏏")
                            .replace(/caps\s\(lock\)/gi, "⇪")
                            .replace(/save/gi, "⌘ + S")
                            .replace(/print/gi, "⌘ + P")
                            .replace(/find/gi, "⌘ + F");
  document.getElementById("result").innerHTML = outputValue;
 } 
}

1) What wOxxOm said in the comment: element.keydown(function() { ... }) does not exist. This definitely comes from some jQuery code - you could use that if you add it to your extension, or you could use addEventListener .

2) You declare a function main() , but nothing ever calls it. A good place to call it would be a DOMContentLoaded event listener on document :

document.addEventListener("DOMContentLoaded", main);

function main() {
  /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM