Background script sending multiple messages - google-chrome-extension

I'm new to chrome extensions and I'm trying to send a message from the background script to the content script. However it keeps sending multiple messages and I don't know how to only send one.
manifest.json
{
"name": "Example",
"version": "1.0",
"description": "Test Extension",
"manifest_version": 2,
"background": {
"scripts": ["jquery-3.4.1.min.js","background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"run_at": "document_start",
"js": ["jquery-3.4.1.min.js","popup.js"]
}
],
"browser_action": {
"default_popup": "popup.html",
"default_title": "Testing"
}
}
background.js
chrome.tabs.onUpdated.addListener(function(tabId,info, tab) {
if (info.status == "complete") {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tab.id, {action: "test", message: "test"}
})
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.from == "message1") {
console.log(message)
}
})
});
popup.js
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
if(message.action == "test"){
chrome.runtime.sendMessage({from:"message1",message:message});
}
});
Output:
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}
{from: "message1", message: {…}}

Related

Notification is not showing up

I read this and trying to make simple extension that is displaying notification, so I wrote the below:
// background.js
let color = '#3aa757';
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ color });
});
chrome.contextMenus.create({
"id": "sampleContextMenu",
"title": "Sample Context Menu",
"contexts": ["selection"],
});
// Example of a simple user data object
const user = {
username: 'demo-user'
};
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// 2. A page requested user data, respond with a copy of `user`
if (message === 'get-user-data') {
showStayHydratedNotification()
sendResponse(user);
}
});
function showStayHydratedNotification() {
chrome.notifications.create('NOTFICATION_ID', {
type: 'basic',
iconUrl: '../m.png',
title: 'notification title',
message: 'notification message',
priority: 2,
buttons: [
{
title: 'Yes'
},
{
title: 'No'
}
]
})
}
And
//content-script
document.body.style.backgroundColor = 'orange';
console.log('Hello')
// 1. Send the background a message requesting the user's data
chrome.runtime.sendMessage('get-user-data', (response) => {
// 3. Got an asynchronous response with the data from the background
console.log('received user data', response);
// initializeUI(response);
});
My manifest is:
{
"name": "Getting Started Example",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "js/background.js"
},
"permissions": ["storage", "activeTab", "contextMenus", "scripting", "alarms", "notifications"],
"options_page": "html/options.html",
"action": {
"default_popup": "html/popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"exclude_matches": ["*://*/*business*"],
"run_at": "document_idle",
"css": ["css/my-styles.css"],
"js": ["js/content-script.js"]
}
]
}
The extension structure is:
When I load the page, everything in the extension is working fine, except the notification, it is not showing up, and I'm not getting any error:
What could be the mistake I made?

Sending a message to chrome extension from a web page. Chrome.runtime.lastError

I want to send a message from a content script injected in a web page to the background of the Chrome extension, but getting the famous chrome.runtime.lastError with error message 'Could not establish connection. Receiving end does not exist.'
I have the next manifest.json
{
"manifest_version": 2,
"name": "Sample Name",
"version": "1.0.0",
"description": "Sample description",
"short_name": "Short Sample Name",
"permissions": ["tabs", "https://google.com/*", "activeTab", "declarativeContent", "storage"],
"externally_connectable": {
"ids": ["{my_extension_id}"],
"matches": ["https://www.google.com/*"]
},
"content_scripts": [
{
"ids": ["{my_extension_id}"],
"matches": ["https://www.google.com/*"],
"js": [
"content.js"
],
"css": ["test.css"]
}
],
"browser_action": {
"default_title": "Sample title",
"default_popup": "popup.html",
"default_icon": {
"16": "icons/icon16.png",
"32": "icons/icon32.png"
}
}
}
the next content.js
const extensionId = "{my_extension_id}";
const url = window.location.href;
function ping() {
chrome.runtime.sendMessage(extensionId, "ping", (response) => {
if (chrome.runtime.lastError) {
console.log("chrome.runtime.lastError again...");
setTimeout(ping, 1000);
} else {
chrome.runtime.sendMessage(
extensionId,
{ url: url },
function (response) {
console.log(response);
}
);
}
});
}
ping();
and the next background.js
chrome.app.runtime.onLaunched.addListener(function () {
chrome.app.window.create("window.html", {
outerBounds: {
width: 500,
height: 500,
},
});
});
chrome.runtime.onConnect.addListener((port) => {
console.log("connected ", port);
port.onMessageExternal.addListener(function (request, sender, sendResponse) {
if (blocklistedWebsite.includes(sender.url)) return;
sendResponse({
success: true,
msg: "I have received your message",
});
});
});
const blocklistedWebsite = [];
chrome.runtime.onMessageExternal.addListener(function (request, sender, sendResponse) {
sendResponse({
success: true,
msg: "I have received your message",
});
});
I tried to do it correct, but now I'm getting a message about chrome.runtime.lastError every second in the web page console. I use the latest version of Chrome.

chrome.notifications.create is not working inside callback function

popup.js
function start(){
let options = {
type: "basic",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "/icon_128.png"
}
chrome.notifications.create(options);
}
// When the button is clicked, inject function will execute on current page
startButton.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: start,
});
});
manifest.json
{
"name": "Meet Auto Exit Bot",
"description": "Exits meet based on number of people present.",
"version": "1.0",
"manifest_version": 3,
"icons": {
"128": "icon_128.png"
},
"action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"permissions": [
"storage",
"activeTab",
"scripting",
"notifications"
]
}
I am developing a chrome in which I am using chrome notifications to notify users. But I am not able to figure out why chrome.notifications.create is not working inside my start() function. It works when using outside the callback function.

trying to execute JS code on a tab but getting executeScript is undefined [duplicate]

Why is this function from Chrome not working? I'm trying this example:
https://developer.chrome.com/docs/extensions/mv3/content_scripts/#programmatic.
I'm developing an extension for chrome and sending a message from popup.js to service worker background.js and get error in executeScript.
popup.js
chrome.runtime.sendMessage({ from: "newScript"});
manifest.json
{
"manifest_version": 3,
"name": "TennisBet",
"version": "1.0",
"description": "Extrension for bet on tennis.",
"action": {
"default_icon": {
"256": "images/tennis256.png",
"128": "images/tennis128.png",
"64": "images/tennis64.png",
"32": "images/tennis32.png",
"24": "images/tennis24.png",
"16": "images/tennis16.png"
},
"default_popup": "popup/popup.html"
},
"background": {
"service_worker": "background-wrapper.js"
},
"host_permissions": ["*://*/*"],
"permissions": [
"tabs",
"alarms",
"activeTab",
"declarativeContent",
"storage"
]
}
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
switch(request.from){
case "error":
console.log(request.message);
break;
case "checkTabs":
tabsWorker();
break;
case "newScript":
chrome.scripting.executeScript({ // Error in event handler: TypeError: Cannot read property 'executeScript' of undefined
file: "content_scripts/cscript.js"
});
break;
default:
console.log("Message listener status active");
break;
}
});
The executeScript method in ManifestV3 has changed and is now in chrome.scripting API:
https://developer.chrome.com/docs/extensions/reference/scripting/
Add this line in manifest.json:
"permissions": ["scripting"]
background.js
chrome.scripting.executeScript({
target: {tabId: id, allFrames: true},
files: ['content_scripts/cscript.js'],
});

Notifications in Chrome Extension not working

I am working on a Chrome extension, but cannot get notifications working. the workflow is the user right clicks on a link, selects "Send Link" from the extension's context menu, then a confirmation should display as a notification.
I have followed the example posted in another question, but it does not work. No notification is shown, nothing is logged in the console and the chrome.runtime.lastError is always "undefined". It's like the whole thing is just ignored. This is on Windows 10. What am I doing wrong?
script.js
function getlink(info,tab) {
var opt = {
iconUrl: "http://www.google.com/favicon.ico",
type: 'list',
title: 'Primary Title',
message: 'Primary message to display',
priority: 1,
items: [{ title: 'Item1', message: 'This is item 1.'},
{ title: 'Item2', message: 'This is item 2.'},
{ title: 'Item3', message: 'This is item 3.'}]
};
chrome.notifications.create('notify1', opt, function() { console.log('created!'); });
alert(chrome.runtime.lastError); //always undefined
}
chrome.contextMenus.create({
title: "Send link",
contexts:["link"],
onclick: getlink
});
manifest.json
{
"manifest_version": 2,
"version": "1.0",
"name": "ext1",
"description": "Extension1",
"icons": {
"16": "images/img16.png",
"48": "images/img48.png",
"128": "images/img128.png"
},
"browser_action":
{
"default_icon": "images/img128.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"contextMenus",
"*://*/*",
"notifications"
],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"css": ["styles.css"],
"js": ["getDescription.js"]
}
],
"background": {
"scripts": ["script.js"]
}
}

Resources