RandomJay
RandomJay
PD🧩 Plasmo Developers
Created by RandomJay on 10/30/2024 in #🔰newbie
sendToBackground in MAIN world doesn't work even with extensionId provided
Hello, thanks for the great framework! I've almost got my MVP done but have run into a brick wall with content scripts. Following the example on https://docs.plasmo.com/framework/messaging#message-flow, this snippet is what i'm after:
To send a message from a content script thats in the main world you'll have to include your extension's id in the request. Your extension's id can be found in chrome's extension manager window once you've built and added it to your browser.
Following the example above, here's my attempt:
import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

export const config: PlasmoCSConfig = {
matches: ["<all_urls>"],
run_at: "document_idle",
world: "MAIN"
}

window.sendTestResults = async (results) => {
console.log("sending test results", results)
await sendToBackground({
name: "results",
body: {
results
},
extensionId: "my_ext_id"
})
}
import type { PlasmoCSConfig } from "plasmo"

import { sendToBackground } from "@plasmohq/messaging"

export const config: PlasmoCSConfig = {
matches: ["<all_urls>"],
run_at: "document_idle",
world: "MAIN"
}

window.sendTestResults = async (results) => {
console.log("sending test results", results)
await sendToBackground({
name: "results",
body: {
results
},
extensionId: "my_ext_id"
})
}
I have a background/messages/results.ts ready and listening, and i've confirmed that this sendTestResults function IS getting called by my executeScript call in background/index.ts. (Basically, i'm triggering a script in the window context to test for accessibility issues, and i'm called window.sendTestResults in its callback. The function is being triggered because i'm seeing console logs in it!) I keep getting an error: Uncaught (in promise) Error: Extension runtime is not available. I've tried this approach, ports, AND relays, but nothing seems to work in the MAIN world. Does anyone have a working example of a content script in the MAIN world triggering a message in the background script? Or at least a strong recommendation for the Plasmo way to send the results of a function called on the window of the page to my background script? Thanks in advance for the help, i'm at the end of my rope!
73 replies