aboutsummaryrefslogtreecommitdiff
path: root/files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html')
-rw-r--r--files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html317
1 files changed, 317 insertions, 0 deletions
diff --git a/files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html b/files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html
new file mode 100644
index 0000000000..f58f2a5f8c
--- /dev/null
+++ b/files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html
@@ -0,0 +1,317 @@
+---
+title: runtime.onMessage
+slug: Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
+translation_of: Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
+---
+<nav>
+<p>{{AddonSidebar()}}</p>
+
+<p>از این رویداد برای گوش دادن به پیام های بخش دیگری از افزونه خود استفاده کنید.</p>
+</nav>
+
+<p>برخی از موارد مورد استفاده برای مثال:</p>
+
+<ul>
+ <li>در یک content script ، برای گوش دادن به پیام های background script.</li>
+ <li>در یک background script ، برای گوش دادن به پیام های content script</li>
+ <li><strong>در یک صفحه <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Options_pages">options page</a> یا <a href="/en-US/Add-ons/WebExtensions/User_interface_components#Popups">popup</a> script</strong>, برای گوش دادن به پیام هایbackground script.</li>
+ <li><strong>در یک background script</strong>, برای گوش دادن به پیام های options page یا popup script.</li>
+</ul>
+
+<p>برای ارسال پیام که توسط <code>onMessage()</code> listener, از {{WebExtAPIRef("runtime.sendMessage()")}} یا (برای ارسال پیام به یک content script) {{WebExtAPIRef("tabs.sendMessage()")}}.</p>
+
+<div class="blockIndicator note">
+<p>از ایجاد چندین  <code>onMessage()</code> listeners برای همان نوع پیام خودداری کنید, زیرا نظم چندین listeners will fire تضمین نمی شود.</p>
+
+<p>اگر می خواهید تحویل پیام به یک نقطه پایان خاص را تضمین کنید, از روش <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Connection-based_messaging">مبتنی بر اتصال برای پیام استفاده کنید</a>.</p>
+</div>
+
+<p>همراه با message خود, به listener منتقل می شود:</p>
+
+<ul>
+ <li>یک شیء <code>فرستنده</code> که جزئیاتی درباره فرستنده پیام می دهد.</li>
+ <li>یک تابع <code>()sendResponse</code> که می تواند برای ارسال پاسخ به فرستنده استفاده شود.</li>
+</ul>
+
+<p>شما می توانید با فراخوانی تابع <code>()sendResponse</code> در listener خود. <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_a_synchronous_response">مثالی را ببینید</a>.</p>
+
+<p>برای ارسال  response ناهمزمان, دو گزینه وجود دارد:</p>
+
+<ul>
+ <li>رویداد listener را  <code>true</code> برگردانید. این کار باعث می شود تابع <code>()sendResponse</code> پس از بازگشت listener معتبر باشد, بنابراین میتوانید بعدأ آن را صدا بزنید. <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_an_asynchronous_response_using_sendResponse">مثالی را ببینید</a>.</li>
+ <li>return a <code>Promise</code> from the event listener, and resolve when you have the response (or reject it in case of an error). <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/onMessage#Sending_an_asynchronous_response_using_a_Promise">See an example</a>.</li>
+</ul>
+
+<div class="warning">
+<p>بازگشت یک <code>Promise</code> در حال حاضر ترجیح داده می شود, زیرا <code>sendResponse()</code> <a href="https://github.com/mozilla/webextension-polyfill/issues/16#issuecomment-296693219">از مشخصات W3C حذف می شود</a>.</p>
+
+<p>کتابخانه محبوب <a href="https://github.com/mozilla/webextension-polyfill">webextension-polyfill</a> قبلا تابع <code>()sendResponse</code> را از اجزای آن حذف کرده است.</p>
+</div>
+
+<div class="blockIndicator note">
+<p>شما همچنین می توانید از یک روش <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Connection-based_messaging">مبتنی بر اتصال برای تبادل پیام استفاده کنید</a>.</p>
+</div>
+
+<h2 id="Syntax">Syntax</h2>
+
+<pre class="syntaxbox brush:js">browser.runtime.onMessage.addListener(<var>listener</var>)
+browser.runtime.onMessage.removeListener(<var>listener</var>)
+browser.runtime.onMessage.hasListener(<var>listener</var>)
+</pre>
+
+<p>رویکردها سه تابع دارند:</p>
+
+<dl>
+ <dt><code>addListener(<var>listener</var>)</code></dt>
+ <dd>به این رویداد یک listener اضلفه می کند.</dd>
+ <dt><code>removeListener(<var>listener</var>)</code></dt>
+ <dd>listening به این رویداد را متوقف می کند. یک <code><var>listener</var></code> دلیلی است برای حذف listener.</dd>
+ <dt><code>hasListener(<var>listener</var>)</code></dt>
+ <dd>بررسی می کند که حداقل یک listener برای این رویداد ثبت شده باشد. اگر listening وجود داشت <code>true</code> برمیگرداند, در غیر این صورت <code>false</code> را بر میگرداند.</dd>
+</dl>
+
+<h2 id="addListener_syntax">addListener syntax</h2>
+
+<h3 id="پارامترها">پارامترها</h3>
+
+<dl>
+ <dt><code><var>listener</var></code></dt>
+ <dd>
+ <p>یک تابع برگشتی که هنگام وقوع این رویداد فراخوانی می شود. به دلایل زیر این تابع پاس داده می شود:</p>
+
+ <dl class="reference-values">
+ <dt><code><var>message</var></code></dt>
+ <dd><code>object</code>. خود پیام است. این یک شیء با قابلیت JSON-ifiable است.</dd>
+ <dt><code><var>sender</var></code></dt>
+ <dd>یک {{WebExtAPIRef('runtime.MessageSender')}} شیء به نمایندگی از فرستنده پیام.</dd>
+ <dt><code><var>sendResponse</var></code></dt>
+ <dd>
+ <p>یک تابع برای صدا زدن, حداکثر یک بار, برای ارسال پاسخ به <code><var>پیام</var></code>. این تابع یک آرگومان واحد را شامل می شود, که ممکن است هر شیء با قابلیت JSON باشد. این آرگومان به فرستنده پیام ارسال می شود.</p>
+
+ <p>اگر بیش از یک شنونده  <code>onMessage()</code> در همان سند دارید, پس فقط ممکن است یک نفر پاسخی ارسال کند.</p>
+
+ <p>برای ارسال پاسخ همزمان, قبل از بازگشت تابع listener با  <code>sendResponse()</code> تماس بگیرید.</p>
+
+ <p>برای ارسال پاسخ به صورت ناهمزمان:</p>
+
+ <ul>
+ <li>یا یک رفرنس برای آرگومان <code>()sendResponse</code> نگه دارید و  مقدار <code>true</code> را برای تابع listener برگردانید. شما می توانید پس از بازگشت تابع listener، با  <code>()sendResponse</code> تماس بگیرید.</li>
+ <li>یا یک {{jsxref("Promise")}} را از تابع listener برگردانید و  promise  را در صورت آماده بودن پاسخ حل کنید.  این یک روش ترجیحی است.</li>
+ </ul>
+ </dd>
+ </dl>
+
+ <p>تابع  <code><var>listener</var></code> می تواند مقدار Boolean یا  {{jsxref("Promise")}} را برگرداند.</p>
+
+ <div class="blockIndicator note">
+ <p><strong>مهم:</strong> با استفاده از تابع <code>async</code>  با  <code>()addListener</code> تماس نگیرید:</p>
+
+ <pre class="brush: js example-bad">// don't do this
+browser.runtime.onMessage.addListener(
+  async (data, sender) =&gt; {
+ if (data.type === 'handle_me') { return 'done'; }
+ }
+);
+</pre>
+
+ <p>این امر باعث می شود شنونده هر پیامی را که دریافت می کند, به طور موثر همه شنوندگان دیگر را از دریافت و پردازش پیام مسدود می کند.</p>
+
+ <p>اگر می خواهید رویکردی ناهمزمان داشته باشید, به جای این کار از یک  Promise استفاده کنید, مانند مثال زیر:</p>
+
+ <pre class="brush: js example-good">browser.runtime.onMessage.addListener(
+  (data, sender) =&gt; {
+ if (data.type === 'handle_me') {
+  return Promise.resolve('done');
+  }
+ }
+);
+</pre>
+ </div>
+ </dd>
+</dl>
+
+<h2 id="سازگاری_مرورگر">سازگاری مرورگر</h2>
+
+<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>
+
+<p>{{Compat("webextensions.api.runtime.onMessage()")}}</p>
+
+<h2 id="Examples">Examples</h2>
+
+<h3 id="Simple_example">Simple example</h3>
+
+<p>This content script listens for click events on the web page. If the click was on a link, it messages the background page with the target URL:</p>
+
+<pre class="brush: js">// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+ if (e.target.tagName != "A") {
+ return;
+ }
+ browser.runtime.sendMessage({"url": e.target.href});
+}
+</pre>
+
+<p>The background script listens for these messages and displays a notification using the <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/notifications">notifications</a></code> API:</p>
+
+<pre class="brush: js">// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+ browser.notifications.create({
+ "type": "basic",
+ "iconUrl": browser.extension.getURL("link.png"),
+ "title": "You clicked a link!",
+ "message": message.url
+ });
+}
+</pre>
+
+<h3 id="Sending_a_synchronous_response">Sending a synchronous response</h3>
+
+<p>This content script sends a message to the background script when the user clicks on the page. It also logs any response sent by the background script:</p>
+
+<pre class="brush: js">// content-script.js
+
+function handleResponse(message) {
+ console.log(`background script sent a response: ${message.response}`);
+}
+
+function handleError(error) {
+ console.log(`Error: ${error}`);
+}
+
+function sendMessage(e) {
+ const sending = browser.runtime.sendMessage({content: "message from the content script"});
+ sending.then(handleResponse, handleError);
+}
+
+window.addEventListener("click", sendMessage);</pre>
+
+<p>Here is a version of the corresponding background script, that sends a response synchronously, from inside in the listener:</p>
+
+<pre class="brush: js">// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+ console.log(`content script sent a message: ${request.content}`);
+ sendResponse({response: "response from background script"});
+}
+
+browser.runtime.onMessage.addListener(handleMessage);</pre>
+
+<p>And here is another version which uses {{jsxref("Promise.resolve()")}}:</p>
+
+<pre class="brush: js">// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+ console.log(`content script sent a message: ${request.content}`);
+ return Promise.resolve({response: "response from background script"});
+}
+
+browser.runtime.onMessage.addListener(handleMessage);</pre>
+
+<h3 id="Sending_an_asynchronous_response_using_sendResponse">Sending an asynchronous response using sendResponse</h3>
+
+<p>Here is an alternative version of the background script from the previous example. It sends a response asynchronously after the listener has returned. Note <code>return true;</code> in the listener: this tells the browser that you intend to use the <code>sendResponse</code> argument after the listener has returned.</p>
+
+<pre class="brush: js">// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+ console.log(`content script sent a message: ${request.content}`);
+ setTimeout(() =&gt; {
+ sendResponse({response: "async response from background script"});
+ }, 1000);
+ return true;
+}
+
+browser.runtime.onMessage.addListener(handleMessage);
+</pre>
+
+<h3 id="Sending_an_asynchronous_response_using_a_Promise">Sending an asynchronous response using a Promise</h3>
+
+<p>This content script gets the first <code>&lt;a&gt;</code> link on the page and sends a message asking if the link's location is bookmarked. It expects to get a Boolean response (<code>true</code> if the location is bookmarked, <code>false</code> otherwise):</p>
+
+<pre class="brush: js">// content-script.js
+
+const firstLink = document.querySelector("a");
+
+function handleResponse(isBookmarked) {
+ if (isBookmarked) {
+ firstLink.classList.add("bookmarked");
+ }
+}
+
+browser.runtime.sendMessage({
+ url: firstLink.href
+}).then(handleResponse);</pre>
+
+<p>Here is the background script. It uses <code>{{WebExtAPIRef("bookmarks.search()")}}</code> to see if the link is bookmarked, which returns a {{jsxref("Promise")}}:</p>
+
+<pre class="brush: js">// background-script.js
+
+function isBookmarked(message, sender, response) {
+ return browser.bookmarks.search({
+ url: message.url
+ }).then(function(results) {
+ return results.length &gt; 0;
+ });
+}
+
+browser.runtime.onMessage.addListener(isBookmarked);</pre>
+
+<p>If the asynchronous handler doesn't return a Promise, you can explicitly construct a promise. This rather contrived example sends a response after a 1-second delay, using <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">Window.setTimeout()</a></code>:</p>
+
+<pre class="brush: js">// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+ return new Promise(resolve =&gt; {
+ setTimeout( () =&gt; {
+ resolve({response: "async response from background script"});
+ }, 1000);
+ });
+}
+
+browser.runtime.onMessage.addListener(handleMessage);</pre>
+
+<p>{{WebExtExamples}}</p>
+
+<div class="note"><strong>Acknowledgements</strong>
+
+<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/runtime#event-onMessage"><code>chrome.runtime</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/runtime.json"><code>runtime.json</code></a> in the Chromium code.</p>
+
+<p>Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.</p>
+</div>
+
+<div class="hidden">
+<pre class="brush: js">// Copyright 2015 The Chromium Authors. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+</pre>
+</div>