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
Thebrowser.tabs.sendmessage()
option enables communication between content scripts and the background script in a browser extension. To use this option, follow these steps:
browser.tabs.sendmessage()
method, specifying the tab ID and the message object as arguments.// Content script: browser.tabs.sendMessage({greeting: "Hello from content script!"});
Consider the following points when usingbrowser.tabs.sendmessage()
:
browser.tabs.query()
to get a list of all open tabs.browser.runtime.onMessage.addListener
.To establish communication between a content script and a background script usingbrowser.tabs.sendmessage()
, follow these steps:
browser.runtime.onMessage.addListener
.browser.tabs.sendmessage()
to send messages to specific tabs or all tabs.// 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!"});
Atas ialah kandungan terperinci contoh pilihan pelayar.tabs.sendmessage. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!