'Firefox | Cant send Message from content script to background script
so im playing around with plugins but i have an issue that i cant resolve. So how you can basically understand how this code works is that you click a button inside a popup (background) to initiate the selector mode for images (content-script). If you click on any image on the current site, this image is converted to an base64 encoded dataurl and should be sent back to the background script. But the last process dosent seem to work at all. When i sent something back to my background script it says that the recieving end dosent exist. Thanks already for the help :)
Error Message: Error: Could not establish connection. Receiving end does not exist.
background.js
browser.runtime.onMessage.addListener(recieveImage)
document.getElementById("convImg2PDF").addEventListener("click", () => {
let executing = browser.tabs.executeScript({
file: "../clickp.js"
})
executing.then(querySelectorMode)
})
const sendSelectorMode = (tabs) => {
browser.tabs.sendMessage(tabs[0].id, {
command: "startSelMode",
})
}
const querySelectorMode = (result) => {
let querying = browser.tabs.query({
active: true,
currentWindow: true
})
querying.then(sendSelectorMode)
}
function recieveImage (request, sender, sendResponse) {
browser.tabs.create({
url:"https://example.org"
});
}
content-script.js
const initSelMode = (request, sender, sendResponse) => {
var images = document.querySelectorAll("img")
for(var i = 0; i < images.length; i++){
images[i].dataset.clickp = i
images[i].addEventListener("click", clickImg)
}
}
function clickImg () {
var body = document.querySelector("body")
var obj = document.createElement("p")
body.appendChild(obj)
toDataURL(this.src, function(url){
body.innerText = url
var sendDataUrl = browser.runtime.sendMessage({
"dataurl": "123"
})
sendDataUrl.then(handleResponse, handleError)
})
}
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
function handleResponse(message) {
console.log(`Message from the background script: ${message.response}`);
}
function handleError(error) {
console.log(`Error: ${error}`);
}
browser.runtime.onMessage.addListener(initSelMode)
manifest.json {
"manifest_version": 2,
"name": "clickP",
"version": "0.1",
"description": "",
"icons": {
"48": "placeholder"
},
"permissions": [
"activeTab",
"tabs"
],
"browser_action": {
"default_icon": {
"19": "placeholder",
"38": "placeholder"
},
"default_title": "clickP",
"default_popup": "./src/popup/controlP.html"
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
