Monday, June 3, 2024
75
rated 0 times [  77] [ 2]  / answers: 1 / hits: 36371  / 10 Years ago, thu, october 2, 2014, 12:00:00

I am trying to send a message from a content script to the background script in a chrome extension that triggers a rich notification to open. I can already achieve this but it breaks the rest of my extension.



In my content script I have a call to chrome.extension.sendMessage inside of which I load my extension code. This was all working fine until I added my notification code, I decided to use chrome Rich Notifications API as I would like to have buttons in my notification eventually, and I am led to believe that only the background script can open the rich notification, hence the need for messages. If I comment out the chrome.runtime.OnMessage.addListener function in background.js my extension logic loads properly again, so something about that call is conflicting with the chrome.extension.sendMessage function in inject.js.



Can anyone explain why this happens and how to fix it?



A simplified version of my code is as follows:



manifest.json



{
name: Test,
version: 0.0.1,
manifest_version: 2,
description: Test
permissions: [
notifications
],
background: {
persistent: false,
scripts: [background.js]
},
content_scripts: [
{
matches: [
mywebsite/*
],
js: [
inject.js,
]
}
],
web_accessible_resources: [
notificationIcon.png
]
}


background.js



chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.type == notification)
chrome.notifications.create('notification', request.options, function() { });
});


inject.js



chrome.extension.sendMessage({}, function(response) {
//code to initialize my extension
});

//code to send message to open notification. This will eventually move into my extension logic
chrome.runtime.sendMessage({type: notification, options: {
type: basic,
iconUrl: chrome.extension.getURL(icon128.png),
title: Test,
message: Test
}});

More From » google-chrome-extension

 Answers
21

The problem was caused because my listener in background.js was not returning a response. So the function response of my chrome.extension.sendMessage was never being executed.



I changed my background.js to be:



chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == worktimer-notification)
chrome.notifications.create('worktimer-notification', request.options, function() { });

sendResponse();
});

[#69266] Monday, September 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
payne

Total Points: 527
Total Questions: 108
Total Answers: 88

Location: Tajikistan
Member since Thu, Apr 14, 2022
2 Years ago
payne questions
Thu, Sep 3, 20, 00:00, 4 Years ago
Tue, Aug 18, 20, 00:00, 4 Years ago
Thu, Oct 11, 18, 00:00, 6 Years ago
;