嗨,我遇到了一个非常奇怪的问题。
我有一个基本的Chrome扩展程序,其默认的popup.html文档定义如下:
<html>
<head>
<script type="text/javascript">
function disp() {
document.getElementById("test").innerHTML = "Bye";
}
</script>
</head>
<body>
<p id="test">Hello</p>
<button type="button" onclick="disp()">'Twas Nice to meet you</button>
</body>
</html>
在浏览器中独立运行html文件后,它会按预期运行:单击该按钮可更改 p 标记的文本。但是,通过使用chrome扩展,在弹出窗口中按钮似乎没有响应
这是与普通弹出窗口或我的代码特定的东西有关吗?
答案 0 :(得分:8)
虽然您已经发现可以规避内联脚本&#34;问题&#34; (这是一个安全功能),下面是你不这样做的样子。这显示了如何调用通知和基于窗口的对话框。
<强>的manifest.json 强>
{
"name": "Hello World!",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"notifications",
"create",
"tabs"
]
}
<强> popup.html 强>
<!doctype html>
<html>
<head>
<title>Getting Started with 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 for security. -->
<script src="popup.js"></script>
</head>
<body>
<div style="text-align: center;">
<button type="button" id="click">Show Notification</button>
<button type="button" id="dialog">Show Dialog</button>
</div>
</body>
</html>
<强> dialog.html 强>
<!doctype html>
<html>
<head>
<title>Dialog Prompt - Chrome</title>
<style>
body {
overflow: hidden;
margin: 0px;
padding: 0px;
background: white;
}
p {
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<p>This is a dialog prompt.</p>
</body>
</html>
<强> popup.js 强>
var notifier,
dialog;
function showNotify() {
var notify;
if (window.webkitNotifications.checkPermission() == 0) {
notify = window.webkitNotifications.createNotification(
"",
'Notification Test',
'This is a test of the Chrome Notification System. This is only a test.'
);
notify.show();
} else {
window.webkitNotifications.requestPermission();
}
}
function showDialog(){
chrome.windows.create({
url: 'dialog.html',
width: 200,
height: 120,
type: 'popup'
});
}
function init() {
clicker = document.querySelector('#click');
dialog = document.querySelector('#dialog');
clicker.addEventListener('click', showNotify, false);
dialog.addEventListener('click', showDialog, false);
}
document.addEventListener('DOMContentLoaded', init);
您可以在此处找到要下载的文件:
答案 1 :(得分:1)
<head>
<script src="yourjsfile.js"></script> //All our functions are defined here
<script src="jquery.js"></script> // This is the jquery
</head>
这里不允许调用函数,如onclick,onkeydown,onkeyup等......
<body>
<p id="test">Hello</p>
<button type="button" id="btn">Twas Nice to meet you</button>
</body>
在上面 &#34; onclick =&#34;不允许使用disp()&#34; , 应该分配一个ID 强>
所以我们需要创建事件,定义必须从.js文件
创建所以你应该写一个像 yourjsfile.js
的js文件document.addEventListener('DOMContentLoaded', function () {
$("#btn").on("click",function(){
disp();
});
});
function disp() {
document.getElementById("test").innerHTML = "Bye";
}