[英]Loading JavaScript in a Chrome Extension
這是我的第一篇SO文章,也是我第一次制作Chrome擴展程序。 我已經閱讀了很多文檔,但是我仍然不確定如何使它起作用。 以下是我的html和js文件。 我希望能夠在源框中鍵入一些內容,並在結果區域中實時打印出單詞。 我已經在本地主機上測試了此代碼,因此我知道它可以工作,但是由於某種原因,它起了chrome擴展的作用。
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>
這是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)wOxxOm在注釋中所說的內容: element.keydown(function() { ... })
不存在。 這肯定來自某些jQuery代碼-如果將其添加到擴展中,則可以使用它,也可以使用addEventListener
。
2)您聲明一個函數main()
,但從未調用它。 調用它的一個好地方是document
上的DOMContentLoaded
事件偵聽器:
document.addEventListener("DOMContentLoaded", main);
function main() {
/* ... */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.