2016-12-07 84 views
0

我目前正在工作一個Chrome擴展,它將通知如果getElementId不在頁面中......並且不幸的是豐富的通知未在內容腳本中顯示。我應該使用Message Passing嗎?豐富的通知不工作

load.js

con = document.getElementById('content'); 

if (con !=null){ 

    var options = { 

    type:"basic", 
    title:"Error", 
    message:"Error", 
    iconUrl:"logo1.png" 
} 

chrome.notifications.create(options, callback); 

function callback() 
{ 

    console.log('yey'); 
} 

} 

manifest.json的

{ 
    "manifest_version": 2, 

    "name": "CRM Online Chrome Extension", 
    "description": "License authentication key for the clients.", 
    "version": "1.0", 

"background": { 
     "scripts": [ 
      "background.js" 




     ], 
     "persistent": true 
    }, 


     "content_scripts":[ 
{ 


    "matches":[ "*://*/*", 
     "*://*/*" 
    ], 
    "js":["payload.js","load.js"] 

} 


    ], 

    "browser_action": { 
     "default_title": "Sample", 
     "default_icon": "logo1.png", 
     "default_popup": "popup.html" 

    }, 
    "permissions": [ 
     "notifications", 
     "tabs", 
     "*://*/*", 
     "*://*/*" 






    ] 


    // "options_page": "option.html" 
} 
+0

'chrome.notification' API是不是由內容腳本進行訪問。你應該傳遞一個消息到後臺頁面,後者會調用'chrome.notification'函數。 –

+0

我明白你的想法,但我不知道該怎麼做。因爲這是第一個我將創建一個擴展,所以我不知道如何語法。如果你給出一個示例語法,對你來說可以嗎? – dionell

+0

@dionell,這個問題包含的代碼與[此問題提前5小時提問]中包含的代碼非常相似(http://stackoverflow.com/q/41009764/3773011)。這是一個團體項目嗎?學校任務? – Makyen

回答

2

您從您的內容腳本到後臺頁面有send a message和後者可以創建於該通知接收消息。

例如:

background.js

chrome.runtime.onMessage.addListener(function(message){ 
    if (message.value == "contentPresent"){ //if the message received is the one we sent from our content script 
     chrome.notifications.create({ //create notificacion 
      type:"basic", 
      title:"Error", 
      message:"Error", 
      iconUrl:"logo1.png" 
     }, function(){ 
       console.log("yey"); 
     }); 
    } 
}); 

content.js

if (document.getElementById("content")) { //if the element with id "content" is found... 
     chrome.runtime.sendMessage({value:"contentPresent"}); //send a message to the background script 
} 
+0

感謝您的幫助。它可以工作,但我想知道或瞭解更多信息那麼你可以向我解釋一下嗎? – dionell

+0

@dionell如果解決方案工作,那麼我認爲你應該接受他的答案,關於它是如何工作的 - 這是一個漫長的故事https://developer.chrome.com/extensions/messaging – Viney

+0

如果內容腳本檢測到id爲「content」的元素,它[發送消息](https://developer.chrome.com/extensions/runtime#method-sendMessage)到後臺腳本。當後臺腳本收到來自內容腳本,它會創建通知。 –

相關問題