我是构建 chrome 扩展的新手,我遇到了这个问题。
背景:
我必须写拼音,但不幸的是,Microsoft Word、Google Docs 和 Apple Pages 没有提供一种方便的方式来写拼音重音。我经常不得不在 Google 文档和在线拼音编辑器之间来回切换,http://www.chinese-tools.com/tools/pinyin-editor.html .我想构建一个 Chrome 扩展程序,这样我就不必在标签之间切换,但我遇到了一个问题。
问题:
在我的 popup.html 上,我有一个 <script></script>
从 http://www.chinese-tools.com 获取 JavaScript 文件.我无法下载它并将其用作本地文件,因为如果我这样做,脚本将无法正确执行。当我将 popup.html 作为本地主机网站进行测试时,它运行良好。但是,该脚本不会在 Chrome 扩展程序上加载。
list :
{
"name": "Pinyin Editor",
"description": "A built-in Pinyin Editor so you don't have to go to chinese-tools.com.",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "A built-in Pinyin Editor."
},
"manifest_version": 2
}
popup.html:
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript1.2" src="http://www.chinese-tools.com/jdd/public/documents/js/carch.js"></script>
</head>
<body>
<form name="conversion" id="conversion">
<textarea name="saisie" id="saisie" cols="80" rows="5" class="ctpinyintextarea" onkeyup="transcrire()" /></textarea>
<br />
</form>
</body>
</html>
问题是 <script language="JavaScript1.2" src="http://www.chinese-tools.com/jdd/public/documents/js/carch.js"></script>
在 popup.html 上拒绝加载 Chrome 扩展程序。我觉得 list 上的 content_scripts 或后台脚本可能有效,但我不知道如何合并它。
最佳答案
您不能简单地在扩展页面中包含外部脚本文件。这将 violate the default Content Security Policy .
对于通过 https
提供的脚本,可以 relax the policy ;但出于安全原因,http
来源是被禁止的:拦截请求和注入(inject)恶意代码太容易了。
就是说,这个特定的脚本如果包含在本地就可以正常工作。比如,将它保存到扩展文件夹中的文件 carch.js
中,并将其包含在 src="carch.js"
中。
那么行不通的是内联代码,即 HTML 中的 onkeyup="transcrire()"
,如 xMort 所述。也是a violation of CSP那cannot be relaxed .
相反,您必须删除它并将其添加到 carch.js
:
// Wait until DOM is ready and element exists
document.addEventListener("DOMContentLoaded", function(event) {
// Attach the listener
document.getElementById("saisie").addEventListener("keyup", transcrire);
});
将来,为了帮助您调试弹出窗口的问题,请查看此 Debugging Tutorial .
关于javascript - Chrome 扩展 : html has external javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25863374/