In this case, you can open a long-lived channel from your content script to an extension page or vice versa using nnect or nnect, respectively. Sometimes it's useful to have a conversation that lasts longer than a single request and response. For information on converting callbacks to promises and for using them in extensions, see our own article. The sendMessage() function's callback will be invoked automatically if no handlers return true or if the sendResponse() callback is garbage-collected.įor information on using promises, see Promises on MDN. If you're using callbacks, the sendResponse() callback is only valid if used synchronously, or if the event handler returns true to indicate that it will respond asynchronously. All other responses to that event will be ignored.įor new extensions you should prefer promises over callbacks. If multiple pages are listening for onMessage events, only the first to call sendResponse() for a particular event will succeed in sending the response. ![]() Sending a request from a content script looks like this: You cannot use both a promise and a callback. For backward compatibility, you can alternatively pass a callback as the last argument. To handle the response, use the returned Promise. This lets you send a one-time JSON-serializable message from a content script to the extension, or vice versa. If you only need to send a single message to another part of your extension (and optionally get a response back), use the simplified ndMessage() method or ndMessage() method. That is covered in the cross-extension messages section. It is also possible to send a message to another extension if you know its ID. There is a simple API for one-time requests and a more complex API for long-lived connections to exchange multiple messages within shared context. A message can contain any valid JSON object (null, boolean, number, string, array, or object). Either side can listen for messages sent from the other end, and respond on the same channel. ![]() For example, an RSS reader extension might use content scripts to detect the presence of an RSS feed on a page, then notify the background page in order to display a page action icon for that page.Ĭommunication between extensions and their content scripts works by using message passing. Since content scripts run in the context of a web page and not the extension, they often need some way of communicating with the rest of the extension.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |