2010-08-21 26 views
6

我試圖從內容腳本中顯示一個簡單的桌面通知代碼,但它似乎沒有工作..我在maifest.json文件中添加了權限。從內容腳本中顯示它們是否有限制?來自內容腳本的桌面通知

回答

2

是的,通知使用Chrome特定的API,而內容腳本僅適用於一般JavaScript等... background page是所有特定於Chrome的API都可以運行的地方...首先,您需要註冊背景在manifest.json文件頁面 - 這樣的:

"background_page": "background.html", 

另外在清單文件,允許所需的權限:

"permissions": [ "notifications" ], 

然後你在後臺頁面腳本應該是這樣的:

<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> 
+0

大..謝謝大衛:) – sharath 2010-08-23 19:09:23

+0

如果你設置permiss在您的擴展清單中通知離子,您無需檢查權限。 http://code.google.com/chrome/extensions/notifications.html – npdoty 2010-08-28 05:45:42

+1

沒有真正解釋如何顯示源自內容腳本的桌面通知。 – 2011-04-16 09:32:32

8

您無法直接通過內容腳本顯示通知。 但是,您可以通過背景頁面顯示它們。

manifest.js應該是這個樣子:

{ 
"name": "Notify This", 
"version": "0.1", 
"permissions": [ 
    "notifications" 
], 
"background_page": "background.html", 
"content_scripts": [ 
    { 
    "matches": ["http://www.example.com/*"], 
    "js": ["contentscript.js"] 
    } 
] 
} 

然後使用chrome.extension.sendRequest()

// in your contentscript.js 
chrome.extension.sendRequest({msg: "Sup?"}, function(response) { // optional callback - gets response 
    console.log(response.returnMsg); 
}); 

而在接收端,你應該有一個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 
    }); 
+0

以下看到我的回答謝謝我終於完成了這樣的工作。他們可能只是允許來自內容腳本的桌面通知。人們在蘋果公司對這樣封閉的API感到惱火,但它不像谷歌那樣網絡意味着更開放...... – 2011-05-31 15:14:28

+0

這是我希望根據問題標題得到的答案。謝謝! – 2011-08-24 19:50:07