PlasmoHQ / plasmo

🧩 The Browser Extension Framework
https://www.plasmo.com
MIT License
10.14k stars 350 forks source link

[BUG] Can not send message from content script to background via @plasmohq/messaging #846

Closed kingname closed 8 months ago

kingname commented 8 months ago

What happened?

A bug happened!

// content.tsx

...
const resp = await sendToBackground({
          name: "getRulesByUrl",
          body: {
            url: window.location.href
          },
          extensionId: "jgcgphlmbjhdhhaamkmiddgbfbkbknan"
        })
        console.log(resp)
        setRules(resp);
// background/getRulesByUrl.ts

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

const handler: PlasmoMessaging.MessageHandler = async (req, res) => {
    const name = req.name;
    const url = req.body.url;
    const domain = new URL(url).hostname;
    let rules;
    if (url === 'google.com') {
        console.log('hit greenhouse.io! return rules...');
        rules = {
            xxx: true
        }
        res.send(rules)
    }
}

export default handler;

background could not receive any message. instead, an error occur:

image

Version

Latest

What OS are you seeing the problem on?

MacOSX

What browsers are you seeing the problem on?

Microsoft Edge

Relevant log output

Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received

(OPTIONAL) Contribution

Code of Conduct

kingname commented 8 months ago

P.S.: It works well when I send message from popup.tsx to background.

Only error from content script to background.

Acorn221 commented 8 months ago

Hi there, have you tried doing something like this?

 if (url === 'google.com') {
        console.log('hit greenhouse.io! return rules...');
        rules = {
            xxx: true
        }
        res.send(rules)
    }
    res.send("err, not google"); // ensure a response is sent back in every case

I think if your content script is in the "isolated" world, which it appears to be in, the problem is caused by no response being sent back from your message handler

kingname commented 8 months ago

@Acorn221 Good point. I will make a try this evening. However, why does popup.tsx work well?

Acorn221 commented 8 months ago

I can't be sure without seeing the code! Maybe your popup handler always returns something?

kingname commented 8 months ago

@Acorn221 You save me. By using your advice, it works like a charm.