Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist - google-chrome-extension

I am trying to pass message from background to content script but it is showing error
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
I have tried too many solutions but nothing work. Here actually I am trying to create side panel in chrome extension for that I am passing message background to content script. My content script file is side-panel.js
background.js
chrome.action.onClicked.addListener((tab) => {
chrome.tabs.sendMessage(tab.id, "toggle");
console.log("message sent");
});
content (side-panel.js)
console.log("side-panel script loaded");
chrome.runtime.onMessage.addListener(function (msg, sender) {
if (msg == "toggle") {
console.log("message received");
toggle();
}
});
var iframe = document.createElement("iframe");
iframe.style.background = "green";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.style.border = "0px";
iframe.src = chrome.runtime.getURL("popup.html");
document.body.appendChild(iframe);
function toggle() {
if (iframe.style.width == "0px") {
iframe.style.width = "400px";
} else {
iframe.style.width = "0px";
}
}
manifest.json
{
"version": "1.0",
"manifest_version": 3,
"name": "test",
"key": "ahhechlhmhicciahdcegooimkdnhbphh",
"background": {
"service_worker": "background.js"
},
"action": {},
"content_scripts": [
{
"matches": [
"https://*/*",
"http://*/*"
],
"js": [
"side-panel.js"
]
}
],
"web_accessible_resources": [
{
"resources": [
"popup.html"
],
"matches": [
"https://*/*",
"http://*/*"
],
"extension_ids": [
"ahhechlhmhicciahdcegooimkdnhbphh"
]
}
]
}

Related

How to pass the entire DOM of the current page to background.js using contentScript?

How do I pass the entire DOM content of Codechef.com to the background.js via contentScript?
I just want to get the problem tag of codechef question. This will help me to fetch the problem code. For this I need to query the dom.
{
"manifest_version": 3,
"name": "CodechefNotifier",
"version": "1.0",
"description": "Notifier for CodeChef",
"action": {
"default_popup": "index.html"
},
"permissions": [
"webRequest", "debugger", "tabs", "<all_urls>", "notifications", "scripting",
"activeTab"
],
"host_permissions": [
"https://www.codechef.com/"
],
"background": {
"service_worker": "background.js"
},
"content_scripts":[
{
"matches":["<all_urls>"],
"js":["contentScript.js"]
}
]
}
const button = document.createElement('button');
button.textContent = 'Greet me!'
document.body.insertAdjacentElement('afterbegin', button);
var tags = [ "h1" ];
var all_headings = [];
var h1s = document.querySelectorAll("h1");
all_headings.push(document.body.innerHTML);
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?codechef\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...w
window.addEventListener('load',function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
I want to pass dom content to the background script

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.

Can't load html file from Chrome extension file system

I'm trying to load an HTML file from the file system of my Chrome extension. I've added "modal.html" as a web accessible resource in my manifest:
{
"name": "Test Extension",
"action": {},
"manifest_version": 3,
"version": "0.1",
"description": "Just learning for now",
"permissions": [
"activeTab",
"scripting",
],
"background": {
"service_worker": "background.js"
},
"web_accessible_resources": [
{
"resources": [ "modal.html" ],
"matches": [ "https://mypage.co.uk/*" ]
}
]
}
My background.js file tries to load modal.html with an xhr:
function initPage() {
let node = document.createElement("div");
node.setAttribute("id", "mySpecialId");
document.body.appendChild(node);
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.runtime.getURL('modal.html'), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.getElementById("mySpecialId").innerText = xhr.responseText;
}
}
xhr.send();
}
chrome.action.onClicked.addListener((tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: initPage
});
});
I get the error:
Denying load of chrome-extension://lmdjgmkmficfccbahcpgnmaplajdljid/modal.html. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
I'm sure this is a really basic problem, but I just can't figure it out.
I got this working by adding the use_dynamic_url key in the web_accessible_resources declaration:
"web_accessible_resources": [
{
"resources": [ "modal.html" ],
"matches": [ "https://www.mypage.co.uk/*" ],
"use_dynamic_url": true
}
]
I don't yet understand why this worked though!
Edit: This was a bug in Chrome. The original code was correct and worked after a reboot.

My chrome extension is not working on Edge

I have a piece of code which works fine on chrome. I did the following step mentioned here.
I'm able to load it properly, but the code doesn't run properly.
In the background console only the url gets printed, no other consoles or alerts work.
Please any help will be appreciated ! Please
window.onload = function() {
console.log("blah1");
var port = browser.runtime.connect({name: "knockknock"});
port.postMessage({request: "sendData"});
port.onMessage.addListener(function(msg) {
console.log("blah2");
if(msg != null){
}
});
}
var sendData = null;
var url = null;
browser.webRequest.onBeforeRequest.addListener(function(details) {
if(details != null && sendData == null && details.url.includes("www")){
console.log(details.url);
sendData = details.url;
}
},
{urls: ["<all_urls>"]},
["blocking", "requestBody"]
);
browser.runtime.onConnect.addListener(function(port) {
console.log("inside addListener")
port.onMessage.addListener(function(msg) {
if (msg.request == "sendData"){
console.log("sendData : ", sendData);
port.postMessage(sendData);
}else if (msg.answer == null){
sendData = null;
}
});
});
My manifest file
{
"manifest_version": 2,
"name": "test",
"version": "1.0.0",
"author": "medha",
"icons": {
"48": "esso.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"permissions": [ "webRequest", "webRequestBlocking", "webNavigation", "tabs", "<all_urls>", "storage"],
"-ms-preload": {
"backgroundScript": "backgroundScriptsAPIBridge.js",
"contentScript": "contentScriptsAPIBridge.js"
}
}
I tested and found that if we remove window.onload then the extension will work well in Edge Legacy. It will print all the consoles.
You could set content.script run at document_idle. It's equal to window.onload and you do not need to listen for the window.onload event. For more detailed information, you could refer to this article.
My manifest.json is like below:
{
"manifest_version": 2,
"name": "test",
"version": "1.0.0",
"author": "medha",
"icons": {
"48": "esso.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"run_at": "document_idle",
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [ "webRequest", "webRequestBlocking", "webNavigation", "tabs", "<all_urls>", "storage"],
"-ms-preload": {
"backgroundScript": "backgroundScriptsAPIBridge.js",
"contentScript": "contentScriptsAPIBridge.js"
}
}

Resources