我决定制作自己的 google chrome 扩展程序。
我正在尝试计算用户提供的文本中的单词和字母。
由于某种原因,当我点击计数时,我看不到任何输出
我的代码中没有语法错误(使用括号调试器检查),只是一些逻辑错误
这是我的manifest.json 文件
{
"manifest_version": 2,
"name": "Count Words In Text",
"description": "This extension allows the user to count words in given input",
"version": "0.0",
"icons": {"128":"icon.png"},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Count Text!"
},
"permissions": [
]
}
这是我的 HTML 文件,popup.html
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<title>Count Text!</title>
<style type="text/css">
body {
margin: 10px;
white-space: nowrap;
}
h1 {
font-size: 15px;
}
#container {
align-items: center;
display: flex;
justify-content: space-between;
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script src="popup.js"></script>
</head>
<body>
<h1>TEXT COUNTER</h1>
<div id="container">
<input type="text" id="a" value=""></input><br>
<button onclick="words()">Count!</button><br>
<input type="text" value="" id="b"></input>
</div>
</body>
</html>
这是我的 javascript 文件,你可能知道我不能在 html 中使用内联脚本,所以我必须制作一个单独的 JS 文件
/*global document*/
function words(){
var a = document.getElementById("a").value;
var b = a.split(" ");
var c = a.split("");
var d = b.length;
var e = c.length;
document.getElementById("b").innerHTML="Number of Letters: "+e+"\n"+"Number of Words: "+d;
}
元素的布局等都是正确的,只是功能不起作用...似乎我的函数甚至没有被调用,请告知是否有任何解决方案。谢谢您
编辑:
我刚刚在控制台上找到了这个,感谢@Titus
“拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“script-src 'self' blob: filesystem: chrome-extension-resource:”。要么是 'unsafe-inline' 关键字,要么是哈希值 ('sha256 -...') 或随机数 ('nonce-...') 需要启用内联执行。”
最佳答案
您自己承认您不能使用内联脚本,但您使用:
<button onclick="words()">
这是内联脚本。 将其更改为
<button id="myButton">
并将其添加到您的 popup.js 文件中:
document.getElementById("myButton").onclick = words;
此外,移动 <script src="popup.js">
标记到 <body>
的底部,在最后进行解析。
关于javascript - 谷歌浏览器扩展程序中的单词和字母计数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589893/