In the process of creating a Chrome extension, I have encountered an issue regarding communication between two content scripts. One script is loaded on the main page, while the other is on an external page within an iframe that I manage. To enable bidirectional communication between these scripts, I am working on implementing the Messaging API.
From what I gather, it is recommended to have each page communicate through background.js. This is the approach I am currently trying to implement. My initial focus is on verifying if messages are being successfully transmitted, but I keep running into the following error:
Error: Attempting to use a disconnected port object
The error seems to be linked to the line "page_post.postMessage(msg)" in background.js. Could the issue be related to using multiple ports?
menu.js
var port = chrome.runtime.connect({name: "menuport"});
port.postMessage({source: "menu", status: "ready", id: menu_id});
port.onMessage.addListener(function(msg) {
console.log('MenuJS')
console.log(msg)
});
page.js
var page_port = chrome.runtime.connect({name: "pageport"});
page_port.postMessage({source: "page", status: "ready"});
page_port.onMessage.addListener(function(msg) {
console.log('PageJS')
console.log(msg)
});
background.js
var menu_port = chrome.runtime.connect({name: "menuport"});
var page_port = chrome.runtime.connect({name: "pageport"});
chrome.runtime.onConnect.addListener(function(menu_port) {
menu_port.onMessage.addListener(function(msg) {
console.log('BGJS')
console.log(msg)
page_port.postMessage(msg);
});
});
chrome.runtime.onConnect.addListener(function(page_port) {
page_port.onMessage.addListener(function(msg) {
console.log(msg)
});
});