How to and do i need to ensure message from my extension?

How should I ensure messages are coming from my own extension in my content scripts. I am talking about when using browser.runtime.onMessage.addListener.

Do I just hardcheck the sender id against my own? Or is there a way to programmatically get my own extensions id from the content script? Or another way.

Any help appreciated. Thanks!

I don’t think other extensions can send you messages to that listener.
For that there is this API:

Quick answer: no. You don’t need to check that.

A longer answer and to expand on what @juraj.masiar said:

When sending messages, you can use runtime.sendMessage() to send them to any extension based on its id:

Sends a single message to event listeners within your extension or a different extension.

If sending to your extension, omit the extensionId argument. The runtime.onMessage event will be fired in each page in your extension, except for the frame that called runtime.sendMessage .

from MDN on runtime.sendMessage()

When receiving and listening to messages, runtime.onMessage only listens to messages sent by your extension:

Use this event to listen for messages from another part of your extension.

from MDN runtime.onMessage

and if you want to listen to messages from other extensions, as Juraj mentioned, you use runtime.onMessageExternal

Use this event to listen for messages from other extensions or web pages.

from MDN runtime.onMessageExternal

1 Like

Now that we got the main question answered in previous messages, I want to answer this separately. Even though it’s not needed for this use case of yours, it might be needed in the future.

You can access your extension id with runtime.id

A string representing the add-on ID. If the extension specifies an ID in its browser_specific_settings manifest.json key, runtime.id contains that value. Otherwise, runtime.id contains the ID that was generated for the extension.

1 Like

Thanks guys for the answers. I actually looked at the documentation you linked not long before making this post. But I did not take in the information properly. I’m working on my first extension and taking in a lot of information at once.

I really appreciate the help with my basic questions.

No worries, this is exactly the right place to ask these kind of questions!

It’s great to hear you’re building your first extension!

1 Like