I am trying to send a variable from a background script to a content script that is associated with an HTML page. The content script updates the HTML content with the variable received from the background script.
The problem is that I am getting this error message:
Could not establish connection. Receiving end does not exist.
The background script main.js
:
const browser = chrome ? chrome : browser;
browser.tabs.onUpdated.addListener((tabId,tab) => { //Burası bizim tab’lerimizi dinliyor eğer youtube açlılırsa haber veriyor content script’e.
debugger
if(tab.url && tab.url.includes("youtube.com/watch")){
const queryParameters = tab.url.split("?")[1];
const urlParameters = new URLSearchParams(queryParameters);
setTimeout(() => {
browser.tabs.sendMessage(tabId, {
type: "NEW",
videoId: urlParameters.get("v") //unique olan videoId sayesinde storage etmemiz kolay olacak.
})
}, 1000);
}
});
The content-script.js
:
browser.runtime.onMessage.addListener((obj, sender, response) => { //Mesajı dinleyen kısım burasıdır.
const { type, value, videoId } = obj; //destructuring obj içindeki type ve value değerlerini alıyoruz.
if (type === "NEW") {
currentVideo = videoId;
newVideoLoaded();
}
else if (type === "PLAY") {
youtubePlayer.currentTime = value;
}
else if (type === "DELETE") {
currentVideoBookmarks = currentVideoBookmarks.filter((b) => b.time != value);
browser.storage.sync.set({ [currentVideo]: JSON.stringify(currentVideoBookmarks) });
response(currentVideoBookmarks);
}
});
The manifest.json
:
{
"name": "Youtube BookMark Manager",
"version": "0.1.0",
"description": "Saving timestaps in YT videos",
"permissions": ["storage", "tabs"],
"host_permissions": ["https://*.youtube.com/*"],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"web_accessible_resources": [
{
"resources": [
"assets/bookmark.png",
"assets/play.png",
"assets/delete.png",
"assets/save.png"
],
"matches": ["https://*.youtube.com/*"]
}
],
"action": {
"default_icon": {
"16": "assets/ext-icon.png",
"24": "assets/ext-icon.png",
"32": "assets/ext-icon.png"
},
"default_title": "Youtube BookMark Manager",
"default_popup": "popup.html"
},
"manifest_version": 3
}
Can you help me?