我正在尝试重新创建this tutorial中显示的页面。
代码如下:
if (!('Notification' in window)) {
document.getElementById('wn-unsupported').classList.remove('hidden');
document.getElementById('button-wn-show-preset').setAttribute('disabled', 'disabled');
document.getElementById('button-wn-show-custom').setAttribute('disabled', 'disabled');
} else {
var log = document.getElementById('log');
var notificationEvents = ['onclick', 'onshow', 'onerror', 'onclose'];
function notifyUser(event) {
var title;
var options;
event.preventDefault();
if (event.target.id === 'button-wn-show-preset') {
title = 'Email received';
options = {
body: 'You have a total of 3 unread emails',
tag: 'preset',
icon: 'http://www.audero.it/favicon.ico'
};
} else {
title = document.getElementById('title').value;
options = {
body: document.getElementById('body').value,
tag: 'custom'
};
}
Notification.requestPermission(function () {
var notification = new Notification(title, options);
notificationEvents.forEach(function (eventName) {
notification[eventName] = function (event) {
log.innerHTML = 'Event "' + event.type + '" triggered for notification "' + notification.tag + '"<br />' + log.innerHTML;
};
});
});
}
document.getElementById('button-wn-show-preset').addEventListener('click', notifyUser);
document.getElementById('button-wn-show-custom').addEventListener('click', notifyUser);
document.getElementById('clear-log').addEventListener('click', function () {
log.innerHTML = '';
});
}
&#13;
*
{
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body
{
max-width: 500px;
margin: 2em auto;
padding: 0 0.5em;
font-size: 20px;
}
h1
{
text-align: center;
}
.hidden
{
display: none;
}
#custom-notification
{
margin-top: 1em;
}
label
{
display: block;
}
input[name="title"],
textarea
{
width: 100%;
}
input[name="title"]
{
height: 2em;
}
textarea
{
height: 5em;
}
.buttons-wrapper
{
text-align: center;
}
.button-demo
{
padding: 0.5em;
margin: 1em;
}
#log
{
height: 200px;
width: 100%;
overflow-y: scroll;
border: 1px solid #333333;
line-height: 1.3em;
}
.author
{
display: block;
margin-top: 1em;
}
&#13;
<h1>Web Notifications API</h1>
<span id="wn-unsupported" class="hidden">API not supported</span>
<form id="custom-notification" action="">
<label for="title">Title:</label>
<input type="text" id="title" name="title" />
<label for="body">Body:</label>
<textarea id="body" name="body"></textarea>
<div class="buttons-wrapper">
<button id="button-wn-show-preset" class="button-demo">Show Preset Notification</button>
<input type="submit" id="button-wn-show-custom" class="button-demo" value="Show Custom Notification" />
</div>
</form>
<h3>Log</h3>
<div id="log"></div>
<button id="clear-log" class="button-demo">Clear log</button>
&#13;
这似乎在网站上链接的live demo中正常工作。
但是,如果我在本地运行相同的代码,它就无法正常工作。我收到了error
事件已被触发的日志消息,而不是通知。我在上面的代码段中观察到相同的行为。
这是与Web通知API有关,还是我做错了什么。请帮忙。
顺便说一句,我在两种情况下都使用最新版本的Chrome(60.0.x)。