Struggling with Plasmo Messaging API: Sending Message from CSUI to BGSW Issue

Hey guys, I've tried so far to understand how Plasmo Messaging API works (from CSUI to BGSW) and although I read through the whole Doc again and again I still miss some key understanding. Long story short, I try to send to the background a message 'clipboards' via a
useEffect
useEffect
from
content.tsx
content.tsx
:
useEffect(() => {
//extensionId is defined as the CSUI injected in the main world
sendToBackground({name:"clipboards", extensionId: 'kceanhfnepllnfmbdmdppmefbhmhlpie'}).then((response) => {
if (response && !response.error) {
setClipboards(response.clipboards || []);
} else {
console.error("Error:", response.error);
message.error("Error retrieving clipboards data.");
}
}).catch((error) => {
console.error("Error", error);
message.error("Communication error with background.");
});
}, []);
useEffect(() => {
//extensionId is defined as the CSUI injected in the main world
sendToBackground({name:"clipboards", extensionId: 'kceanhfnepllnfmbdmdppmefbhmhlpie'}).then((response) => {
if (response && !response.error) {
setClipboards(response.clipboards || []);
} else {
console.error("Error:", response.error);
message.error("Error retrieving clipboards data.");
}
}).catch((error) => {
console.error("Error", error);
message.error("Communication error with background.");
});
}, []);
The structure of my background folder is the following:
/background
L/messages
L clipboards.ts
L index.ts
/background
L/messages
L clipboards.ts
L index.ts
`
index.ts
index.ts
is left empty. The code of
clipboards.ts
clipboards.ts
is the following:
// Importez axios ou une autre bibliothèque HTTP si vous effectuez des requêtes HTTP dans ce gestionnaire de message
import axios from "axios";
import type { PlasmoMessaging } from "@plasmohq/messaging"


const API_URL = "http://localhost:3000/clipboards";

// La fonction exportée par défaut est le gestionnaire de message
const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
try {
console.log("Request received");
const response = await axios.get(API_URL, { withCredentials: true });
if (response.status === 200) {
res.send({
success: true,
data: response.data,
});
}
res.send({
success: false,
error: "Non-200 response",
});
} catch (error) {
res.send({
success: false,
error: error.message,
});
}
}

export default handler
// Importez axios ou une autre bibliothèque HTTP si vous effectuez des requêtes HTTP dans ce gestionnaire de message
import axios from "axios";
import type { PlasmoMessaging } from "@plasmohq/messaging"


const API_URL = "http://localhost:3000/clipboards";

// La fonction exportée par défaut est le gestionnaire de message
const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
try {
console.log("Request received");
const response = await axios.get(API_URL, { withCredentials: true });
if (response.status === 200) {
res.send({
success: true,
data: response.data,
});
}
res.send({
success: false,
error: "Non-200 response",
});
} catch (error) {
res.send({
success: false,
error: error.message,
});
}
}

export default handler
` Your help would be highly appreciated!
13 Replies
abhi
abhi8mo ago
Hi @Alix, Did you figure out how that works? I'm stuck at the same stage.
Alix
AlixOP8mo ago
Hey @abhi , the best alternative I have found was not to inject the content script in the Main world.
abhi
abhi8mo ago
I have not explicitly stated to inject into the main world, so I think it is not in the main world, but I am still not able to get a message. I have almost the same structure as you. If you don't mind can you look at below code and let me know If I am doing somthing wrong. content script
import type { PlasmoGetStyle } from "plasmo"
import { sendToBackground } from "@plasmohq/messaging"

import { useState, useEffect } from 'react';
import styles from "data-text:./../styles/controle.css"


export const getStyle: PlasmoGetStyle = () => {
const style = document.createElement("style")
style.textContent = styles;
return style
}

const ControlBar = () => {
const [hover, setHover] = useState(false);


useEffect(() => {
const handleClick = (event) => {
console.log('Clicked: document');
sendToBackground({
name: "capture",
body: {
id: 123
},
extensionId: 'mhoigcfemcodbcmlomehjkheajjjkgii' // find this in chrome's extension manager
}).then((response) => {console.log("response", response)});

};

document.addEventListener('click', handleClick);
console.log('Event listener added');





// Cleanup function to remove the event listener when the component unmounts
return () => {
document.removeEventListener('click', handleClick);
console.log('Event listener removed');
};
}, []);


return (
<div
className="control-bar"
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
onClick={(e) => e.stopPropagation()}
>
<button className="main-button">Main</button>
{hover && (
<>
{Array.from({ length: 4 }).map((_, i) => (
<button key={i} className="option-button">Option {i + 1}</button>
))}
</>
)}
</div>
);
};

export default ControlBar;
import type { PlasmoGetStyle } from "plasmo"
import { sendToBackground } from "@plasmohq/messaging"

import { useState, useEffect } from 'react';
import styles from "data-text:./../styles/controle.css"


export const getStyle: PlasmoGetStyle = () => {
const style = document.createElement("style")
style.textContent = styles;
return style
}

const ControlBar = () => {
const [hover, setHover] = useState(false);


useEffect(() => {
const handleClick = (event) => {
console.log('Clicked: document');
sendToBackground({
name: "capture",
body: {
id: 123
},
extensionId: 'mhoigcfemcodbcmlomehjkheajjjkgii' // find this in chrome's extension manager
}).then((response) => {console.log("response", response)});

};

document.addEventListener('click', handleClick);
console.log('Event listener added');





// Cleanup function to remove the event listener when the component unmounts
return () => {
document.removeEventListener('click', handleClick);
console.log('Event listener removed');
};
}, []);


return (
<div
className="control-bar"
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
onClick={(e) => e.stopPropagation()}
>
<button className="main-button">Main</button>
{hover && (
<>
{Array.from({ length: 4 }).map((_, i) => (
<button key={i} className="option-button">Option {i + 1}</button>
))}
</>
)}
</div>
);
};

export default ControlBar;
capture.ts
import type { PlasmoMessaging } from "@plasmohq/messaging"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
console.log("called")

res.send({
imageURI: "ajsh"
})


}

export default handler


import type { PlasmoMessaging } from "@plasmohq/messaging"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
console.log("called")

res.send({
imageURI: "ajsh"
})


}

export default handler


Alix
AlixOP8mo ago
Oh therefore you should remove « extensionId: « … » »
abhi
abhi8mo ago
I was doing that, but it is still not working. I thought maybe it could work, so I tried it, but still no luck.
Alix
AlixOP8mo ago
How is structured your background folder?
abhi
abhi8mo ago
No description
Alix
AlixOP8mo ago
Hmm that sucks I’ll take a closer look at my code see if there’s anything else But genuinely I remember having struggled for days and it miraculously worked at some point
abhi
abhi8mo ago
I am trying different solutions from the internet this morning. Thank you for your help. Let me know if you get anything.
YAGPDB.xyz
YAGPDB.xyz8mo ago
Gave +1 Rep to @Alix (current: #27 - 1)
abhi
abhi8mo ago
Hey It worked after I manually reloaded the extension. Thank you for your help. 🥳
YAGPDB.xyz
YAGPDB.xyz8mo ago
Gave +1 Rep to @Alix (current: #17 - 2)
Alix
AlixOP8mo ago
Nice 👍🏻
Want results from more Discord servers?
Add your server