2016-12-07 62 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)到后台脚本。当后台脚本收到来自内容脚本,它会创建通知。 –

相关问题