sha*_*ath 6 google-chrome google-chrome-extension
我试图从内容脚本显示一个简单的桌面通知代码,但它似乎不起作用..我已在maifest.json文件中添加权限.从内容脚本中显示它们是否有限制?
您无法通过内容脚本直接显示通知.但是,您可以通过后台页面显示它们.
你manifest.js应该是这样的:
{
"name": "Notify This",
"version": "0.1",
"permissions": [
"notifications"
],
"background_page": "background.html",
"content_scripts": [
{
"matches": ["http://www.example.com/*"],
"js": ["contentscript.js"]
}
]
}
Run Code Online (Sandbox Code Playgroud)
然后使用chrome.extension.sendRequest():
// in your contentscript.js
chrome.extension.sendRequest({msg: "Sup?"}, function(response) { // optional callback - gets response
console.log(response.returnMsg);
});
Run Code Online (Sandbox Code Playgroud)
在接收端你应该有一个onRequest监听器:
// in your background.html
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
// Create a simple text notification:
var notify = webkitNotifications.createNotification(
'48.png', // icon url - can be relative
'Hello!', // notification title
request.msg // notification body text
);
notify.show();
setTimeout(function(){ notify.cancel(); },5000);
sendResponse({returnMsg: "All good!"}); // optional response
});
Run Code Online (Sandbox Code Playgroud)
是的,通知使用 Chrome 特定的 API,并且内容脚本仅对一般 javascript 等有效...后台页面是所有 Chrome 特定 API 都能够运行的地方...首先,您需要在manifest.json文件 - 像这样:
"background_page": "background.html",
Run Code Online (Sandbox Code Playgroud)
同样在清单文件中,允许所需的权限:
"permissions": [ "notifications" ],
Run Code Online (Sandbox Code Playgroud)
那么后台页面中的脚本应如下所示:
<script>
setTimeout("setNotification();",1);
function setNotification(){
var n
if (window.webkitNotifications.checkPermission() != 0){
setNotification();
return false;
}
n = window.webkitNotifications.createHTMLNotification('http://www.your-notification-address.com');
n.show();}
</script>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3932 次 |
最近记录: |