Error with messaging

Hey, im trying to send a message from a content script in the main world to the background. For that I have 2 small scripts, that I copied mainly from the docs, but I still cant get it to work. Why? /src/background/messages/ping.ts
import type { PlasmoMessaging } from "@plasmohq/messaging"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
console.log("Ping message received", req.body.id)
const message = "Pong!"

res.send({
message
})
}

export default handler
import type { PlasmoMessaging } from "@plasmohq/messaging"

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
console.log("Ping message received", req.body.id)
const message = "Pong!"

res.send({
message
})
}

export default handler
/src/contents/componentInRealWorld.ts
import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

export const config: PlasmoCSConfig = {
matches: ["https://www.google.com/*"],
world: "MAIN",
run_at: "document_end"
}

async function ping() {
console.log("Component in real world")
const resp = await sendToBackground({
name: "ping",
body: {
id: 123
},
extensionId: "dbihgacbiojmefppibfimnmpabpifldj" // find this in chrome's extension manager
})

console.log(resp)
}

setInterval(ping, 1000)
import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

export const config: PlasmoCSConfig = {
matches: ["https://www.google.com/*"],
world: "MAIN",
run_at: "document_end"
}

async function ping() {
console.log("Component in real world")
const resp = await sendToBackground({
name: "ping",
body: {
id: 123
},
extensionId: "dbihgacbiojmefppibfimnmpabpifldj" // find this in chrome's extension manager
})

console.log(resp)
}

setInterval(ping, 1000)
2 Replies
Saqlain
Saqlain•6mo ago
Were you able to solve this?
Sam
Sam•5mo ago
I had to use a relay to cross the MAIN world boundary. I have a file src/background/messages/tabApi.ts. I have a content script named main-world-handler that registers all the relays. In that file I have
relayMessage({
name: 'tabApi',
body: {},
});
relayMessage({
name: 'tabApi',
body: {},
});
I can then call it from a MAIN world script with await sendToBackgroundViaRelay({name: 'tabAPI', body: {...}})
Want results from more Discord servers?
Add your server