contoh pilihan pelayar.tabs.sendmessage

DDD
Lepaskan: 2024-08-15 14:33:20
asal
179 orang telah melayarinya

This article provides a comprehensive guide on using the browser.tabs.sendmessage() option to enable communication between content scripts and the background script in browser extensions. It outlines the steps for sending and receiving messages, alon

contoh pilihan pelayar.tabs.sendmessage

How to Use browser.tabs.sendmessage() Option to Send Messages to the Background Script?

Thebrowser.tabs.sendmessage()option enables communication between content scripts and the background script in a browser extension. To use this option, follow these steps:

  • In your content script, create a message object containing the data you want to send.
  • Use thebrowser.tabs.sendmessage()method, specifying the tab ID and the message object as arguments.
// Content script: browser.tabs.sendMessage({greeting: "Hello from content script!"});
Salin selepas log masuk

Points to Note When Using browser.tabs.sendmessage() Option

Consider the following points when usingbrowser.tabs.sendmessage():

  • Ensure that the tab ID is valid. You can usebrowser.tabs.query()to get a list of all open tabs.
  • The message object should be serializable, meaning it can be converted into a JSON string.
  • The background script must be listening for messages usingbrowser.runtime.onMessage.addListener.

How to Use browser.tabs.sendmessage() Option to Communicate Between Content Script and Background Script?

To establish communication between a content script and a background script usingbrowser.tabs.sendmessage(), follow these steps:

  • In the content script, define a listener for messages usingbrowser.runtime.onMessage.addListener.
  • In the background script, usebrowser.tabs.sendmessage()to send messages to specific tabs or all tabs.
  • Handle the received messages in the corresponding listener in both the content script and the background script.
// Content script: browser.runtime.onMessage.addListener((request, sender, sendResponse) => { // Handle the received message here }); // Background script: browser.tabs.sendMessage(tabId, {greeting: "Hello from background script!"});
Salin selepas log masuk

Atas ialah kandungan terperinci contoh pilihan pelayar.tabs.sendmessage. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!