From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../add-ons/webextensions/api/runtime/index.html | 168 +++++++++++ .../webextensions/api/runtime/onmessage/index.html | 317 +++++++++++++++++++++ 2 files changed, 485 insertions(+) create mode 100644 files/fa/mozilla/add-ons/webextensions/api/runtime/index.html create mode 100644 files/fa/mozilla/add-ons/webextensions/api/runtime/onmessage/index.html (limited to 'files/fa/mozilla/add-ons/webextensions/api/runtime') diff --git a/files/fa/mozilla/add-ons/webextensions/api/runtime/index.html b/files/fa/mozilla/add-ons/webextensions/api/runtime/index.html new file mode 100644 index 0000000000..62478e3457 --- /dev/null +++ b/files/fa/mozilla/add-ons/webextensions/api/runtime/index.html @@ -0,0 +1,168 @@ +--- +title: runtime +slug: Mozilla/Add-ons/WebExtensions/API/runtime +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Reference + - TopicStub + - WebExtensions + - runtime +translation_of: Mozilla/Add-ons/WebExtensions/API/runtime +--- +
{{AddonSidebar}}
+ +

This module provides information about your extension and the environment it's running in.

+ +

It also provides messaging APIs enabling you to:

+ + + +

Types

+ +
+
{{WebExtAPIRef("runtime.Port")}}
+
Represents one end of a connection between two specific contexts, which can be used to exchange messages.
+
{{WebExtAPIRef("runtime.MessageSender")}}
+
+

Contains information about the sender of a message or connection request.

+
+
{{WebExtAPIRef("runtime.PlatformOs")}}
+
Identifies the browser's operating system.
+
{{WebExtAPIRef("runtime.PlatformArch")}}
+
Identifies the browser's processor architecture.
+
{{WebExtAPIRef("runtime.PlatformInfo")}}
+
Contains information about the platform the browser is running on.
+
{{WebExtAPIRef("runtime.RequestUpdateCheckStatus")}}
+
Result of a call to {{WebExtAPIRef("runtime.requestUpdateCheck()")}}.
+
{{WebExtAPIRef("runtime.OnInstalledReason")}}
+
The reason that the {{WebExtAPIRef("runtime.onInstalled")}} event is being dispatched.
+
{{WebExtAPIRef("runtime.OnRestartRequiredReason")}}
+
The reason that the {{WebExtAPIRef("runtime.onRestartRequired")}} event is being dispatched.
+
+ +

Properties

+ +
+
{{WebExtAPIRef("runtime.lastError")}}
+
This value is set when an asynchronous function has an error condition that it needs to report to its caller.
+
{{WebExtAPIRef("runtime.id")}}
+
The ID of the extension.
+
+ +

Functions

+ +
+
{{WebExtAPIRef("runtime.getBackgroundPage()")}}
+
Retrieves the Window object for the background page running inside the current extension.
+
{{WebExtAPIRef("runtime.openOptionsPage()")}}
+
+

Opens your extension's options page.

+
+
{{WebExtAPIRef("runtime.getManifest()")}}
+
Gets the complete manifest.json file, serialized as an object.
+
{{WebExtAPIRef("runtime.getURL()")}}
+
Given a relative path from the manifest.json to a resource packaged with the extension, returns a fully-qualified URL.
+
{{WebExtAPIRef("runtime.setUninstallURL()")}}
+
Sets a URL to be visited when the extension is uninstalled.
+
{{WebExtAPIRef("runtime.reload()")}}
+
Reloads the extension.
+
{{WebExtAPIRef("runtime.requestUpdateCheck()")}}
+
Checks for updates to this extension.
+
{{WebExtAPIRef("runtime.connect()")}}
+
Establishes a connection from a content script to the main extension process, or from one extension to a different extension.
+
{{WebExtAPIRef("runtime.connectNative()")}}
+
+
Connects the extension to a native application on the user's computer.
+
+
{{WebExtAPIRef("runtime.sendMessage()")}}
+
Sends a single message to event listeners within your extension or a different extension. Similar to {{WebExtAPIRef('runtime.connect')}} but only sends a single message, with an optional response.
+
{{WebExtAPIRef("runtime.sendNativeMessage()")}}
+
Sends a single message from an extension to a native application.
+
{{WebExtAPIRef("runtime.getPlatformInfo()")}}
+
Returns information about the current platform.
+
{{WebExtAPIRef("runtime.getBrowserInfo()")}}
+
Returns information about the browser in which this extension is installed.
+
{{WebExtAPIRef("runtime.getPackageDirectoryEntry()")}}
+
Returns a DirectoryEntry for the package directory.
+
+ +

Events

+ +
+
{{WebExtAPIRef("runtime.onStartup")}}
+
Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started.
+
{{WebExtAPIRef("runtime.onInstalled")}}
+
Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.
+
{{WebExtAPIRef("runtime.onSuspend")}}
+
Sent to the event page just before the extension is unloaded. This gives the extension an opportunity to do some cleanup.
+
{{WebExtAPIRef("runtime.onSuspendCanceled")}}
+
Sent after {{WebExtAPIRef("runtime.onSuspend")}} to indicate that the extension won't be unloaded after all.
+
{{WebExtAPIRef("runtime.onUpdateAvailable")}}
+
Fired when an update is available, but isn't installed immediately because the extension is currently running.
+
{{WebExtAPIRef("runtime.onBrowserUpdateAvailable")}} {{deprecated_inline}}
+
Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.
+
{{WebExtAPIRef("runtime.onConnect")}}
+
Fired when a connection is made with either an extension process or a content script.
+
{{WebExtAPIRef("runtime.onConnectExternal")}}
+
Fired when a connection is made with another extension.
+
{{WebExtAPIRef("runtime.onMessage")}}
+
Fired when a message is sent from either an extension process or a content script.
+
{{WebExtAPIRef("runtime.onMessageExternal")}}
+
Fired when a message is sent from another extension. Cannot be used in a content script.
+
{{WebExtAPIRef("runtime.onRestartRequired")}}
+
Fired when the device needs to be restarted.
+
+ +

Browser compatibility

+ + + +

{{Compat("webextensions.api.runtime")}}

+ +
{{WebExtExamples("h2")}}
+ +
Acknowledgements + +

This API is based on Chromium's chrome.runtime API. This documentation is derived from runtime.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + 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 +--- + + +

برخی از موارد مورد استفاده برای مثال:

+ + + +

برای ارسال پیام که توسط onMessage() listener, از {{WebExtAPIRef("runtime.sendMessage()")}} یا (برای ارسال پیام به یک content script) {{WebExtAPIRef("tabs.sendMessage()")}}.

+ +
+

از ایجاد چندین  onMessage() listeners برای همان نوع پیام خودداری کنید, زیرا نظم چندین listeners will fire تضمین نمی شود.

+ +

اگر می خواهید تحویل پیام به یک نقطه پایان خاص را تضمین کنید, از روش مبتنی بر اتصال برای پیام استفاده کنید.

+
+ +

همراه با message خود, به listener منتقل می شود:

+ + + +

شما می توانید با فراخوانی تابع ()sendResponse در listener خود. مثالی را ببینید.

+ +

برای ارسال  response ناهمزمان, دو گزینه وجود دارد:

+ + + +
+

بازگشت یک Promise در حال حاضر ترجیح داده می شود, زیرا sendResponse() از مشخصات W3C حذف می شود.

+ +

کتابخانه محبوب webextension-polyfill قبلا تابع ()sendResponse را از اجزای آن حذف کرده است.

+
+ +
+

شما همچنین می توانید از یک روش مبتنی بر اتصال برای تبادل پیام استفاده کنید.

+
+ +

Syntax

+ +
browser.runtime.onMessage.addListener(listener)
+browser.runtime.onMessage.removeListener(listener)
+browser.runtime.onMessage.hasListener(listener)
+
+ +

رویکردها سه تابع دارند:

+ +
+
addListener(listener)
+
به این رویداد یک listener اضلفه می کند.
+
removeListener(listener)
+
listening به این رویداد را متوقف می کند. یک listener دلیلی است برای حذف listener.
+
hasListener(listener)
+
بررسی می کند که حداقل یک listener برای این رویداد ثبت شده باشد. اگر listening وجود داشت true برمیگرداند, در غیر این صورت false را بر میگرداند.
+
+ +

addListener syntax

+ +

پارامترها

+ +
+
listener
+
+

یک تابع برگشتی که هنگام وقوع این رویداد فراخوانی می شود. به دلایل زیر این تابع پاس داده می شود:

+ +
+
message
+
object. خود پیام است. این یک شیء با قابلیت JSON-ifiable است.
+
sender
+
یک {{WebExtAPIRef('runtime.MessageSender')}} شیء به نمایندگی از فرستنده پیام.
+
sendResponse
+
+

یک تابع برای صدا زدن, حداکثر یک بار, برای ارسال پاسخ به پیام. این تابع یک آرگومان واحد را شامل می شود, که ممکن است هر شیء با قابلیت JSON باشد. این آرگومان به فرستنده پیام ارسال می شود.

+ +

اگر بیش از یک شنونده  onMessage() در همان سند دارید, پس فقط ممکن است یک نفر پاسخی ارسال کند.

+ +

برای ارسال پاسخ همزمان, قبل از بازگشت تابع listener با  sendResponse() تماس بگیرید.

+ +

برای ارسال پاسخ به صورت ناهمزمان:

+ +
    +
  • یا یک رفرنس برای آرگومان ()sendResponse نگه دارید و  مقدار true را برای تابع listener برگردانید. شما می توانید پس از بازگشت تابع listener، با  ()sendResponse تماس بگیرید.
  • +
  • یا یک {{jsxref("Promise")}} را از تابع listener برگردانید و  promise  را در صورت آماده بودن پاسخ حل کنید.  این یک روش ترجیحی است.
  • +
+
+
+ +

تابع  listener می تواند مقدار Boolean یا  {{jsxref("Promise")}} را برگرداند.

+ +
+

مهم: با استفاده از تابع async  با  ()addListener تماس نگیرید:

+ +
// don't do this
+browser.runtime.onMessage.addListener(
+  async (data, sender) => {
+    if (data.type === 'handle_me') { return 'done'; }
+  }
+);
+
+ +

این امر باعث می شود شنونده هر پیامی را که دریافت می کند, به طور موثر همه شنوندگان دیگر را از دریافت و پردازش پیام مسدود می کند.

+ +

اگر می خواهید رویکردی ناهمزمان داشته باشید, به جای این کار از یک  Promise استفاده کنید, مانند مثال زیر:

+ +
browser.runtime.onMessage.addListener(
+  (data, sender) => {
+    if (data.type === 'handle_me') {
+      return Promise.resolve('done');
+    }
+  }
+);
+
+
+
+
+ +

سازگاری مرورگر

+ + + +

{{Compat("webextensions.api.runtime.onMessage()")}}

+ +

Examples

+ +

Simple example

+ +

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:

+ +
// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+  if (e.target.tagName != "A") {
+    return;
+  }
+  browser.runtime.sendMessage({"url": e.target.href});
+}
+
+ +

The background script listens for these messages and displays a notification using the notifications API:

+ +
// 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
+  });
+}
+
+ +

Sending a synchronous response

+ +

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:

+ +
// 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);
+ +

Here is a version of the corresponding background script, that sends a response synchronously, from inside in the listener:

+ +
// 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);
+ +

And here is another version which uses {{jsxref("Promise.resolve()")}}:

+ +
// 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);
+ +

Sending an asynchronous response using sendResponse

+ +

Here is an alternative version of the background script from the previous example. It sends a response asynchronously after the listener has returned. Note return true; in the listener: this tells the browser that you intend to use the sendResponse argument after the listener has returned.

+ +
// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+  console.log(`content script sent a message: ${request.content}`);
+  setTimeout(() => {
+    sendResponse({response: "async response from background script"});
+  }, 1000);
+  return true;
+}
+
+browser.runtime.onMessage.addListener(handleMessage);
+
+ +

Sending an asynchronous response using a Promise

+ +

This content script gets the first <a> link on the page and sends a message asking if the link's location is bookmarked. It expects to get a Boolean response (true if the location is bookmarked, false otherwise):

+ +
// 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);
+ +

Here is the background script. It uses {{WebExtAPIRef("bookmarks.search()")}} to see if the link is bookmarked, which returns a {{jsxref("Promise")}}:

+ +
// background-script.js
+
+function isBookmarked(message, sender, response) {
+  return browser.bookmarks.search({
+    url: message.url
+  }).then(function(results) {
+    return results.length > 0;
+  });
+}
+
+browser.runtime.onMessage.addListener(isBookmarked);
+ +

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 Window.setTimeout():

+ +
// background-script.js
+
+function handleMessage(request, sender, sendResponse) {
+  return new Promise(resolve => {
+    setTimeout( () => {
+      resolve({response: "async response from background script"});
+    }, 1000);
+  });
+}
+
+browser.runtime.onMessage.addListener(handleMessage);
+ +

{{WebExtExamples}}

+ +
Acknowledgements + +

This API is based on Chromium's chrome.runtime API. This documentation is derived from runtime.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + -- cgit v1.2.3-54-g00ecf