From cbf9c41e5e2e95a2791597872cba3a8a191a8840 Mon Sep 17 00:00:00 2001 From: "Queen Vinyl Da.i'gyu-Kazotetsu" Date: Thu, 27 Jul 2023 00:43:13 -0700 Subject: [PATCH] ja: Format /mozilla/add-ons using Prettier --- .prettierignore | 2 - .../add_a_button_to_the_toolbar/index.md | 37 ++- .../chrome_incompatibilities/index.md | 13 +- .../webextensions/content_scripts/index.md | 80 ++++--- .../content_security_policy/index.md | 15 +- .../extending_the_developer_tools/index.md | 26 ++- .../implement_a_settings_page/index.md | 20 +- .../interact_with_the_clipboard/index.md | 28 +-- .../intercept_http_requests/index.md | 34 ++- .../internationalization/index.md | 6 +- .../manifest.json/commands/index.md | 2 +- .../manifest.json/icons/index.md | 18 +- .../manifest.json/options_ui/index.md | 4 +- .../manifest.json/page_action/index.md | 2 +- .../manifest.json/theme/index.md | 10 +- .../web_accessible_resources/index.md | 6 +- .../webextensions/match_patterns/index.md | 22 +- .../webextensions/modify_a_web_page/index.md | 41 ++-- .../webextensions/native_manifests/index.md | 23 +- .../webextensions/native_messaging/index.md | 120 +++++----- .../context_menu_items/index.md | 13 +- .../user_interface/devtools_panels/index.md | 18 +- .../user_interface/extension_pages/index.md | 6 +- .../user_interface/notifications/index.md | 8 +- .../user_interface/options_pages/index.md | 6 +- .../user_interface/sidebars/index.md | 2 +- .../work_with_the_bookmarks_api/index.md | 43 ++-- .../webextensions/working_with_files/index.md | 30 +-- .../working_with_the_tabs_api/index.md | 217 ++++++++---------- .../your_first_webextension/index.md | 2 - .../your_second_webextension/index.md | 16 +- 31 files changed, 415 insertions(+), 455 deletions(-) diff --git a/.prettierignore b/.prettierignore index 7b7a38947c0e1d..a0e0bf934d5a10 100644 --- a/.prettierignore +++ b/.prettierignore @@ -46,9 +46,7 @@ build/ /files/ja/learn/css/**/*.md /files/ja/learn/javascript/**/*.md /files/ja/learn/server-side/**/*.md -/files/ja/mozilla/**/*.md /files/ja/mdn/**/*.md -/files/ja/mozilla/add-ons/**/*.md /files/ja/mozilla/add-ons/webextensions/api/**/*.md /files/ja/web/api/**/*.md /files/ja/web/css/**/*.md diff --git a/files/ja/mozilla/add-ons/webextensions/add_a_button_to_the_toolbar/index.md b/files/ja/mozilla/add-ons/webextensions/add_a_button_to_the_toolbar/index.md index cbf693652b24e2..22363f94eebe82 100644 --- a/files/ja/mozilla/add-ons/webextensions/add_a_button_to_the_toolbar/index.md +++ b/files/ja/mozilla/add-ons/webextensions/add_a_button_to_the_toolbar/index.md @@ -23,7 +23,6 @@ WebExtension API では、こうしたボタンの種類は "ブラウザーア ```json { - "description": "Demonstrating toolbar buttons", "manifest_version": 2, "name": "button-demo", @@ -39,7 +38,6 @@ WebExtension API では、こうしたボタンの種類は "ブラウザーア "32": "icons/page-32.png" } } - } ``` @@ -59,7 +57,7 @@ These icons are from the [bitsies!](https://www.iconfinder.com/iconsets/bitsies) ```js function openPage() { browser.tabs.create({ - url: "https://developer.mozilla.org" + url: "https://developer.mozilla.org", }); } @@ -70,7 +68,7 @@ browser.browserAction.onClicked.addListener(openPage); ここで完全な拡張機能は次のようです: -```html +```plain button/ icons/ page-16.png @@ -89,7 +87,6 @@ button/ ```json { - "description": "Demonstrating toolbar buttons", "manifest_version": 2, "name": "button-demo", @@ -103,7 +100,6 @@ button/ "32": "icons/page-32.png" } } - } ``` @@ -116,21 +112,20 @@ button/ さてポップアップを作らねばなりません。"popup" というディレクトリーを作成してその中に "choose_page.html" というファイルを作ります。中身は次の通り: ```html - + - - + + - -
developer.mozilla.org
-
support.mozilla.org
-
addons.mozilla.org
- - - + +
developer.mozilla.org
+
support.mozilla.org
+
addons.mozilla.org
+ + ``` @@ -139,7 +134,8 @@ button/ "popup" ディレクトリーに"choose_page.css" というファイルを作って、次の中身を入れます: ```css -html, body { +html, +body { width: 300px; } @@ -152,7 +148,7 @@ html, body { } .page-choice:hover { - background-color: #CFF2F2; + background-color: #cff2f2; } ``` @@ -161,16 +157,15 @@ html, body { 次に、"popup" ディレクトリーに"choose_page.js" ファイルを作成し、次の中身を入れます: ```js -document.addEventListener("click", function(e) { +document.addEventListener("click", function (e) { if (!e.target.classList.contains("page-choice")) { return; } var chosenPage = "https://" + e.target.textContent; browser.tabs.create({ - url: chosenPage + url: chosenPage, }); - }); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md b/files/ja/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md index c4f070ffa1b912..ba8ee24378120c 100644 --- a/files/ja/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md +++ b/files/ja/mozilla/add-ons/webextensions/chrome_incompatibilities/index.md @@ -16,13 +16,13 @@ Webextension を用いた拡張機能は Chrome や Opera の拡張機能と互 Chrome では、拡張機能は `chrome` ネームスペースを使って特権 JavaScript API にアクセスします: ```js -chrome.browserAction.setIcon({path: "path/to/icon.png"}); +chrome.browserAction.setIcon({ path: "path/to/icon.png" }); ``` WebExtensions は同等の API に `browser` ネームスペースを使ってアクセスします: ```js -browser.browserAction.setIcon({path: "path/to/icon.png"}); +browser.browserAction.setIcon({ path: "path/to/icon.png" }); ``` 多くの API は非同期です。 Chrome では、非同期 API はコールバックを使用して値を返し、{{WebExtAPIRef("runtime.lastError")}}がエラーを通知します: @@ -36,10 +36,7 @@ function logCookie(c) { } } -chrome.cookies.set( - {url: "https://developer.mozilla.org/"}, - logCookie -); +chrome.cookies.set({ url: "https://developer.mozilla.org/" }, logCookie); ``` 同様の WebExtensions API では [promises](/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise) を利用します: @@ -53,9 +50,7 @@ function logError(e) { console.error(e); } -var setCookie = browser.cookies.set( - {url: "https://developer.mozilla.org/"} -); +var setCookie = browser.cookies.set({ url: "https://developer.mozilla.org/" }); setCookie.then(logCookie, logError); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/content_scripts/index.md b/files/ja/mozilla/add-ons/webextensions/content_scripts/index.md index d4c38045ff3057..4e8df67d884d22 100644 --- a/files/ja/mozilla/add-ons/webextensions/content_scripts/index.md +++ b/files/ja/mozilla/add-ons/webextensions/content_scripts/index.md @@ -40,12 +40,12 @@ l10n: 次の 3 つの方法のいずれかを使用して、ウェブページにコンテンツスクリプトを読み込むことができます。 -1. - インストール時に、URL パターンに一致するページ内へ。 - - : `manifest.json` の [`content_scripts`](/ja/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) キーを使用して、URL が[指定されたパターンに一致する](/ja/docs/Mozilla/Add-ons/WebExtensions/Match_patterns)ページをロードするたびにコンテンツスクリプトを読み込むようブラウザーに依頼できます。 -2. - 実行時に、URL パターンに一致するページ内へ。 - - : {{WebExtAPIRef("contentScripts")}} API を使って、URL が[指定されたパターンに一致する](/ja/docs/Mozilla/Add-ons/WebExtensions/Match_patterns)ページを読み込むたびにコンテンツスクリプトを読み込むようブラウザーに依頼できます。これは方法 1 と似ていますが、実行時にコンテンツスクリプトを追加/削除できる点が異なります。) -3. - 実行時に、特定のタブへ。 - - : Manifest V2 において、[`tabs.executeScript()`](/ja/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) API を使用するか、Manifest V3 において、{{WebExtAPIRef("scripting.executeScript()")}} を使用すると、必要なときにコンテンツスクリプトを特定のタブに読み込むことができます。(ユーザーが[ブラウザーアクション](/ja/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action)をクリックした場合など。) +1. インストール時に、URL パターンに一致するページ内へ。 + - : `manifest.json` の [`content_scripts`](/ja/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts) キーを使用して、URL が[指定されたパターンに一致する](/ja/docs/Mozilla/Add-ons/WebExtensions/Match_patterns)ページをロードするたびにコンテンツスクリプトを読み込むようブラウザーに依頼できます。 +2. 実行時に、URL パターンに一致するページ内へ。 + - : {{WebExtAPIRef("contentScripts")}} API を使って、URL が[指定されたパターンに一致する](/ja/docs/Mozilla/Add-ons/WebExtensions/Match_patterns)ページを読み込むたびにコンテンツスクリプトを読み込むようブラウザーに依頼できます。これは方法 1 と似ていますが、実行時にコンテンツスクリプトを追加/削除できる点が異なります。) +3. 実行時に、特定のタブへ。 + - : Manifest V2 において、[`tabs.executeScript()`](/ja/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) API を使用するか、Manifest V3 において、{{WebExtAPIRef("scripting.executeScript()")}} を使用すると、必要なときにコンテンツスクリプトを特定のタブに読み込むことができます。(ユーザーが[ブラウザーアクション](/ja/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action)をクリックした場合など。) *フレームごと、拡張機能ごとの*グローバルスコープしかありません。これは 1 つのコンテンツスクリプトの変数は、読み込み方にかかわらず、他のコンテンツスクリプトからアクセスできることになります。 @@ -72,7 +72,7 @@ Firefox では、この挙動は [Xray vision](/ja/docs/Mozilla/Add-ons/WebExten 次のようなウェブページを考えてみてください。 ```html - + @@ -101,7 +101,7 @@ window.foo = "This global variable was added by a page script"; // redefine the built-in window.confirm() function window.confirm = () => { alert("The page script has also redefined 'confirm'"); -} +}; ``` 今度は拡張機能がページにコンテンツスクリプトを挿入します。 @@ -114,7 +114,7 @@ let pageScriptPara = document.getElementById("page-script-para"); pageScriptPara.style.backgroundColor = "blue"; // can't see properties added by page-script.js -console.log(window.foo); // undefined +console.log(window.foo); // undefined // sees the original form of redefined properties window.confirm("Are you sure?"); // calls the original window.confirm() @@ -272,7 +272,7 @@ function notifyExtension(e) { if (e.target.tagName !== "A") { return; } - browser.runtime.sendMessage({"url": e.target.href}); + browser.runtime.sendMessage({ url: e.target.href }); } ``` @@ -285,10 +285,10 @@ 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 + type: "basic", + iconUrl: browser.extension.getURL("link.png"), + title: "You clicked a link!", + message: message.url, }); } ``` @@ -328,8 +328,8 @@ function notify(message) { ```js // content-script.js -let myPort = browser.runtime.connect({name:"port-from-cs"}); -myPort.postMessage({greeting: "hello from content script"}); +let myPort = browser.runtime.connect({ name: "port-from-cs" }); +myPort.postMessage({ greeting: "hello from content script" }); myPort.onMessage.addListener((m) => { console.log("In content script, received message from background script: "); @@ -337,7 +337,7 @@ myPort.onMessage.addListener((m) => { }); document.body.addEventListener("click", () => { - myPort.postMessage({greeting: "they clicked the page!"}); + myPort.postMessage({ greeting: "they clicked the page!" }); }); ``` @@ -359,16 +359,18 @@ let portFromCS; function connected(p) { portFromCS = p; - portFromCS.postMessage({greeting: "hi there content script!"}); + portFromCS.postMessage({ greeting: "hi there content script!" }); portFromCS.onMessage.addListener((m) => { - portFromCS.postMessage({greeting: `In background script, received message from content script: ${m.greeting}`}); + portFromCS.postMessage({ + greeting: `In background script, received message from content script: ${m.greeting}`, + }); }); } browser.runtime.onConnect.addListener(connected); browser.browserAction.onClicked.addListener(() => { - portFromCS.postMessage({greeting: "they clicked the button!"}); + portFromCS.postMessage({ greeting: "they clicked the button!" }); }); ``` @@ -379,19 +381,19 @@ browser.browserAction.onClicked.addListener(() => { ```js // background-script.js -let ports = [] +let ports = []; function connected(p) { - ports[p.sender.tab.id] = p + ports[p.sender.tab.id] = p; // … } -browser.runtime.onConnect.addListener(connected) +browser.runtime.onConnect.addListener(connected); browser.browserAction.onClicked.addListener(() => { ports.forEach((p) => { - p.postMessage({greeting: "they clicked the button!"}) - }) + p.postMessage({ greeting: "they clicked the button!" }); + }); }); ``` @@ -422,10 +424,13 @@ let messenger = document.getElementById("from-page-script"); messenger.addEventListener("click", messageContentScript); function messageContentScript() { - window.postMessage({ - direction: "from-page-script", - message: "Message from the page" - }, "*"); + window.postMessage( + { + direction: "from-page-script", + message: "Message from the page", + }, + "*", + ); } ``` @@ -481,15 +486,18 @@ window.addEventListener("message", (event) => { ```js // content-script.js -window.eval('window.x = 1;'); -eval('window.y = 2'); +window.eval("window.x = 1;"); +eval("window.y = 2"); console.log(`In content script, window.x: ${window.x}`); console.log(`In content script, window.y: ${window.y}`); -window.postMessage({ - message: "check" -}, "*"); +window.postMessage( + { + message: "check", + }, + "*", +); ``` このコードは単に変数 x と y を、`window.eval()` と `eval()` を用いて作成し、値をログに出し、ページにメッセージします。 @@ -536,11 +544,11 @@ In page script, window.y: undefined > > console.log = () => { > original(true); -> } +> }; > ``` > > ```js example-bad > // content-script.js calls the redefined version > -> window.eval('console.log(false)'); +> window.eval("console.log(false)"); > ``` diff --git a/files/ja/mozilla/add-ons/webextensions/content_security_policy/index.md b/files/ja/mozilla/add-ons/webextensions/content_security_policy/index.md index d7b75710a9a035..a9aeec12ccf83a 100644 --- a/files/ja/mozilla/add-ons/webextensions/content_security_policy/index.md +++ b/files/ja/mozilla/add-ons/webextensions/content_security_policy/index.md @@ -14,15 +14,14 @@ WebExtension APIs で開発される拡張機能には、既定で適用され ウェブサイトと同様に、拡張機能はさまざまなソースからコンテンツを読み込めます。例えば、ブラウザーアクションのポップアップは HTML 文書として指定できて、通常のウェブページのようにさまざまなソースからの JavaScript と CSS を入れることができます: ```html - + - + - - ``` @@ -66,7 +63,7 @@ WebExtension APIs で開発される拡張機能には、既定で適用され 既定の CSP の下では、拡張機能のローカルにある [\ + ``` これは要求したリソースを読み込みません: 静かに失敗し、このリソースから取ってきたはずのいかなるオブジェクトも見つかりません。この解決方法が 2 つあります: @@ -95,7 +92,9 @@ var f = new Function("console.log('foo');"); 既定の CSP ではインライン JavaScript は実行されません。これは ` + ``` ```html diff --git a/files/ja/mozilla/add-ons/webextensions/extending_the_developer_tools/index.md b/files/ja/mozilla/add-ons/webextensions/extending_the_developer_tools/index.md index 7fd2138837089e..a8425bf070135a 100644 --- a/files/ja/mozilla/add-ons/webextensions/extending_the_developer_tools/index.md +++ b/files/ja/mozilla/add-ons/webextensions/extending_the_developer_tools/index.md @@ -34,10 +34,10 @@ devtools ページには目に見える DOM はありませんが、[` @@ -54,14 +54,16 @@ devtools ウィンドウは、JavaScript デバッガ、ネットワークモニ `devtools.panels.create()` API を使用して、devtools ウィンドウに独自のパネルを作成できます: ```js -browser.devtools.panels.create( - "My Panel", // title - "icons/star.png", // icon - "devtools/panel/panel.html" // content -).then((newPanel) => { - newPanel.onShown.addListener(initialisePanel); - newPanel.onHidden.addListener(unInitialisePanel); -}); +browser.devtools.panels + .create( + "My Panel", // title + "icons/star.png", // icon + "devtools/panel/panel.html", // content + ) + .then((newPanel) => { + newPanel.onShown.addListener(initialisePanel); + newPanel.onHidden.addListener(unInitialisePanel); + }); ``` これにはパネルのタイトル、アイコン、コンテンツの 3 つの引数が必要です。新しいパネルを表す `devtools.panels.ExtensionPanel` オブジェクトに解決される [`Promise`](/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise) を返します。 @@ -94,7 +96,7 @@ const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';"; window.addEventListener("click", () => { browser.runtime.sendMessage({ tabId: browser.devtools.inspectedWindow.tabId, - script: scriptToAttach + script: scriptToAttach, }); }); ``` @@ -104,7 +106,7 @@ window.addEventListener("click", () => { function handleMessage(request, sender, sendResponse) { browser.tabs.executeScript(request.tabId, { - code: request.script + code: request.script, }); } diff --git a/files/ja/mozilla/add-ons/webextensions/implement_a_settings_page/index.md b/files/ja/mozilla/add-ons/webextensions/implement_a_settings_page/index.md index 374458b9c8cb6a..4a10f3d11051c2 100644 --- a/files/ja/mozilla/add-ons/webextensions/implement_a_settings_page/index.md +++ b/files/ja/mozilla/add-ons/webextensions/implement_a_settings_page/index.md @@ -23,7 +23,6 @@ WebExtension API では一般に、設定は [`storage`](/ja/docs/Mozilla/Add-on ```json { - "manifest_version": 2, "name": "Settings example", "version": "1.0", @@ -34,7 +33,6 @@ WebExtension API では一般に、設定は [`storage`](/ja/docs/Mozilla/Add-on "js": ["borderify.js"] } ] - } ``` @@ -60,7 +58,6 @@ document.body.style.border = "10px solid blue"; ```json { - "manifest_version": 2, "name": "Settings example", "version": "1.0", @@ -83,7 +80,6 @@ document.body.style.border = "10px solid blue"; "id": "addon@example.com" } } - } ``` @@ -96,24 +92,21 @@ document.body.style.border = "10px solid blue"; 次に "options.html" を提供する約束をしたので、作成します。"settings" ディレクトリー内にその名前でファイルを作成して、次の中身を与えます: ```html - + - + -
- - + +
- - ``` @@ -125,12 +118,11 @@ document.body.style.border = "10px solid blue"; function saveOptions(e) { e.preventDefault(); browser.storage.sync.set({ - color: document.querySelector("#color").value + color: document.querySelector("#color").value, }); } function restoreOptions() { - function setCurrentChoice(result) { document.querySelector("#color").value = result.color || "blue"; } @@ -163,7 +155,7 @@ document.querySelector("form").addEventListener("submit", saveOptions); > **警告:** バージョン 52 より前の Firefox の [browser.storage.local.get()](/ja/docs/Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/get) のバグにより、下記のコードは機能しません。バージョン 52 より前の Firefox で動作させるには、`onGot()` の中で 2 回出てくる `item.color` を `item[0].color` に変えないといけません。 ```js - function onError(error) { +function onError(error) { console.log(`Error: ${error}`); } diff --git a/files/ja/mozilla/add-ons/webextensions/interact_with_the_clipboard/index.md b/files/ja/mozilla/add-ons/webextensions/interact_with_the_clipboard/index.md index 8346c9191194d8..b5b701817550ac 100644 --- a/files/ja/mozilla/add-ons/webextensions/interact_with_the_clipboard/index.md +++ b/files/ja/mozilla/add-ons/webextensions/interact_with_the_clipboard/index.md @@ -34,7 +34,7 @@ Clipboard API は、拡張機能から任意のデータをクリップボード ページスクリプトの場合、Web API の {{domxref("Permissions", "navigator.permissions")}} を使用して `"clipboard-write"` パーミッションを要求する必要があります。そのパーミッションは、{{domxref("Permissions.query", "navigator.permissions.query()")}} を使って確認することができます。 ```js -navigator.permissions.query({name: "clipboard-write"}).then((result) => { +navigator.permissions.query({ name: "clipboard-write" }).then((result) => { if (result.state === "granted" || result.state === "prompt") { /* write to the clipboard now */ } @@ -47,11 +47,14 @@ navigator.permissions.query({name: "clipboard-write"}).then((result) => { ```js function updateClipboard(newClip) { - navigator.clipboard.writeText(newClip).then(() => { - /* clipboard successfully set */ - }, () => { - /* clipboard write failed */ - }); + navigator.clipboard.writeText(newClip).then( + () => { + /* clipboard successfully set */ + }, + () => { + /* clipboard write failed */ + }, + ); } ``` @@ -62,8 +65,7 @@ function updateClipboard(newClip) { 例えば、以下のような HTML を含むポップアップがあったとします。 ```html - - + ``` `"copy"` ボタンで {{HTMLElement("input")}} 要素の内容をコピーさせるには、次のようなコードを使用します。 @@ -90,7 +92,7 @@ function copy() { } browser.alarms.create({ - delayInMinutes: 0.1 + delayInMinutes: 0.1, }); browser.alarms.onAlarm.addListener(copy); @@ -129,8 +131,9 @@ Clipboard API の {{domxref("Clipboard.readText", "navigator.clipboard.readText( 一度 [Permissions API](/ja/docs/Web/API/Permissions_API) から `"clipboard-read"` パーミッションを取得すると、クリップボードから簡単に読み取ることができるようになります。例えば、このコードのスニペットはクリップボードからテキストを取得し、ID が `"outbox"` の要素の内容をそのテキストで置き換えます。 ```js -navigator.clipboard.readText().then((clipText) => - document.getElementById("outbox").innerText = clipText); +navigator.clipboard + .readText() + .then((clipText) => (document.getElementById("outbox").innerText = clipText)); ``` ### execCommand() を使用する @@ -140,8 +143,7 @@ navigator.clipboard.readText().then((clipText) => このような内容を含む HTML を考えてみましょう。 ```html - - + ``` ユーザーが `"paste"` の {{HTMLElement("button")}} をクリックしたときに、クリップボードから ID が `"output"` の {{HTMLElement("textarea")}} 要素の内容を設定するには、次のようなコードを使用します。 diff --git a/files/ja/mozilla/add-ons/webextensions/intercept_http_requests/index.md b/files/ja/mozilla/add-ons/webextensions/intercept_http_requests/index.md index df2080b1826ce2..8bcb051ab33dce 100644 --- a/files/ja/mozilla/add-ons/webextensions/intercept_http_requests/index.md +++ b/files/ja/mozilla/add-ons/webextensions/intercept_http_requests/index.md @@ -33,10 +33,7 @@ HTTP リクエストへ介入するには {{WebExtAPIRef("webRequest")}} API を "name": "webRequest-demo", "version": "1.0", - "permissions": [ - "webRequest", - "" - ], + "permissions": ["webRequest", ""], "background": { "scripts": ["background.js"] @@ -51,10 +48,9 @@ function logURL(requestDetails) { console.log(`Loading: ${requestDetails.url}`); } -browser.webRequest.onBeforeRequest.addListener( - logURL, - {urls: [""]} -); +browser.webRequest.onBeforeRequest.addListener(logURL, { + urls: [""], +}); ``` ここでは、リクエストを作成する直前に{{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} を利用して、 `logURL()` 関数を呼んでいます。 `logURL()` 関数では、イベントオブジェクトからリクエスト URL を取得し、ブラウザーのコンソールに出力しています。 `{urls: [""]}` [パターン](/ja/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) は、すべての URL に対する HTTP リクエストに介入することを表しています。 @@ -82,7 +78,6 @@ browser.webRequest.onBeforeRequest.addListener( ```json { - "description": "Demonstrating webRequests", "manifest_version": 2, "name": "webRequest-demo", @@ -97,7 +92,6 @@ browser.webRequest.onBeforeRequest.addListener( "background": { "scripts": ["background.js"] } - } ``` @@ -105,13 +99,14 @@ browser.webRequest.onBeforeRequest.addListener( - `webRequestBlocking` を [`permission`](/ja/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) に追加しました。 この特別な権限は、拡張機能がリクエストを変更したいときにリクエストされます。 -- ` 権限を個々の[ホスト権限](/ja/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_権限)に置き換えてください。これはリクエストされた権限数を最小限にするための良い習慣です。 +- ` 権限を個々の[ホスト権限](/ja/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host*権限)に置き換えてください。これはリクエストされた権限数を最小限にするための良い習慣です。 続いて "background.js" を以下のように書き換えます。 ```js let pattern = "https://developer.mozilla.org/*"; -const targetUrl = "https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension/frog.jpg"; +const targetUrl = + "https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_second_WebExtension/frog.jpg"; function redirect(requestDetails) { console.log(`Redirecting: ${requestDetails.url}`); @@ -119,14 +114,14 @@ function redirect(requestDetails) { return; } return { - redirectUrl: targetUrl + redirectUrl: targetUrl, }; } browser.webRequest.onBeforeRequest.addListener( redirect, - {urls:[pattern], types:["image"]}, - ["blocking"] + { urls: [pattern], types: ["image"] }, + ["blocking"], ); ``` @@ -174,7 +169,8 @@ browser.webRequest.onBeforeRequest.addListener( ```js let targetPage = "http://useragentstring.com/*"; -let ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16"; +let ua = + "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16"; function rewriteUserAgentHeader(e) { e.requestHeaders.forEach((header) => { @@ -182,13 +178,13 @@ function rewriteUserAgentHeader(e) { header.value = ua; } }); - return {requestHeaders: e.requestHeaders}; + return { requestHeaders: e.requestHeaders }; } browser.webRequest.onBeforeSendHeaders.addListener( rewriteUserAgentHeader, - {urls: [targetPage]}, - ["blocking", "requestHeaders"] + { urls: [targetPage] }, + ["blocking", "requestHeaders"], ); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/internationalization/index.md b/files/ja/mozilla/add-ons/webextensions/internationalization/index.md index fa08daa1f7c12f..da75ae7a973971 100644 --- a/files/ja/mozilla/add-ons/webextensions/internationalization/index.md +++ b/files/ja/mozilla/add-ons/webextensions/internationalization/index.md @@ -80,9 +80,9 @@ l10n: "message": "You clicked $URL$.", "description": "Tells the user which link they clicked.", "placeholders": { - "url" : { - "content" : "$1", - "example" : "https://developer.mozilla.org" + "url": { + "content": "$1", + "example": "https://developer.mozilla.org" } } } diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/commands/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/commands/index.md index a08b7b712bfecd..8b7411c2f06882 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/commands/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/commands/index.md @@ -117,7 +117,7 @@ slug: Mozilla/Add-ons/WebExtensions/manifest.json/commands 次に、これらのコマンドの最初を下記のようにリッスンできます: ```js -browser.commands.onCommand.addListener(function(command) { +browser.commands.onCommand.addListener(function (command) { if (command == "toggle-feature") { console.log("toggling the feature!"); } diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/icons/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/icons/index.md index d2f82c715b15fb..5fa2d43731d2bc 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/icons/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/icons/index.md @@ -56,18 +56,18 @@ You can use SVG and the browser will scale your icon appropriately. There are cu 1. You need to specify a viewBox in the image. E.g.: - ```html - **メモ:** If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon. diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/options_ui/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/options_ui/index.md index 87c01ce45daa2c..fc41aac70a764d 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/options_ui/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/options_ui/index.md @@ -49,8 +49,8 @@ l10n: `options_ui` キーは次のコンテンツを持つオブジェクトです。 -| `open_in_tab` | `Boolean` | 省略可能。既定値は `false`。`true` の場合、オプションページはブラウザーのアドオンマネージャーに統合されたものではなく、通常のブラウザータブで開かれる。 | -| `page` | `String` | 必須。オプションページの仕様を含む HTML ファイルへのパス。パスは manifest.json 自体への相対パス。 | +| `open_in_tab` | `Boolean` | 省略可能。既定値は `false`。`true` の場合、オプションページはブラウザーのアドオンマネージャーに統合されたものではなく、通常のブラウザータブで開かれる。 | +| `page` | `String` | 必須。オプションページの仕様を含む HTML ファイルへのパス。パスは manifest.json 自体への相対パス。 | diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/page_action/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/page_action/index.md index 2c1da6c485f0be..4f06b340acc2b8 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/page_action/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/page_action/index.md @@ -262,7 +262,7 @@ The `page_action` key is an object that may have any of three properties, all op A page action with just an icon, specified in 2 different sizes. The extension's background scripts can receive click events when the user clicks the icon using code like this: ```js - browser.pageAction.onClicked.addListener(handleClick); +browser.pageAction.onClicked.addListener(handleClick); ``` ```json diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/theme/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/theme/index.md index cd9e0573fa3c6d..a4068742197d9f 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/theme/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/theme/index.md @@ -146,11 +146,11 @@ All URLs are relative to the manifest.json file and cannot reference an external Images should be 200 pixels high to ensure they always fill the header space vertically. -| 名前 | 型 | 説明 | -| ------------------------ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `headerURL` | `String` | Fully optional from Firefox 60 onwards. One of theme_frame or headerURL had to be specified before Firefox 60. Note also that in Firefox 60 onwards, any {{cssxref("text-shadow")}} applied to the header text is removed if no `headerURL` is specified (see [Firefox バグ 1404688](https://bugzil.la/1404688)).The URL of a foreground image to be added to the header area and anchored to the upper right corner of the header area. | -| `theme_frame` | `String` | Fully optional from Firefox 60 onwards. One of theme_frame or headerURL had to be specified before Firefox 60.Alias for `headerURL`, provided for Chrome compatibility. | -| `additional_backgrounds` | `Array` of `String` | オプション An array of URLs for additional background images to be added to the header area and displayed behind the `"headerURL":` image. These images layer the first image in the array on top, the last image in the array at the bottom.既定では all images are anchored to the upper right corner of the header area, but their alignment and repeat behavior can be controlled by properties of `"properties":`. | +| 名前 | 型 | 説明 | +| ------------------------ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `headerURL` | `String` | Fully optional from Firefox 60 onwards. One of theme_frame or headerURL had to be specified before Firefox 60. Note also that in Firefox 60 onwards, any {{cssxref("text-shadow")}} applied to the header text is removed if no `headerURL` is specified (see [Firefox バグ 1404688](https://bugzil.la/1404688)).The URL of a foreground image to be added to the header area and anchored to the upper right corner of the header area. | +| `theme_frame` | `String` | Fully optional from Firefox 60 onwards. One of theme_frame or headerURL had to be specified before Firefox 60.Alias for `headerURL`, provided for Chrome compatibility. | +| `additional_backgrounds` | `Array` of `String` | オプション An array of URLs for additional background images to be added to the header area and displayed behind the `"headerURL":` image. These images layer the first image in the array on top, the last image in the array at the bottom.既定では all images are anchored to the upper right corner of the header area, but their alignment and repeat behavior can be controlled by properties of `"properties":`. | ### colors diff --git a/files/ja/mozilla/add-ons/webextensions/manifest.json/web_accessible_resources/index.md b/files/ja/mozilla/add-ons/webextensions/manifest.json/web_accessible_resources/index.md index c58d6cf70b7350..f865ab93c6b662 100644 --- a/files/ja/mozilla/add-ons/webextensions/manifest.json/web_accessible_resources/index.md +++ b/files/ja/mozilla/add-ons/webextensions/manifest.json/web_accessible_resources/index.md @@ -44,7 +44,7 @@ slug: Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources 例えば、拡張機能に images/my-image.png にある画像ファイルを入れたい場合、このようにします: -```html +```plain my-extension-files/ manifest.json my-background-script.js @@ -60,8 +60,8 @@ my-extension-files/ このファイルは次の URL で利用できます: -```html -moz-extension:///images/my-image.png" +```url +moz-extension:///images/my-image.png ``` `` は拡張機能の ID **ではありません。**これは各ブラウザーインスタンス用にランダムに生成されます。これはウェブサイトがインストールしている拡張機能を調べることで指紋を取ることを防止します。 diff --git a/files/ja/mozilla/add-ons/webextensions/match_patterns/index.md b/files/ja/mozilla/add-ons/webextensions/match_patterns/index.md index 73d79a9e7ef73a..184671c76232ed 100644 --- a/files/ja/mozilla/add-ons/webextensions/match_patterns/index.md +++ b/files/ja/mozilla/add-ons/webextensions/match_patterns/index.md @@ -63,19 +63,19 @@ _path_ の値は、URL パスに [URL クエリーストリング](https://en.wi ## 例 -| パターン | マッチする例 | マッチしない例 | | -| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | +| パターン | マッチする例 | マッチしない例 | | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | ``すべての URL にマッチ | `http://example.org/` `https://a.org/some/path/` `ws://sockets.somewhere.org/` `wss://ws.example.com/stuff/` `ftp://files.somewhere.org/` `ftps://files.somewhere.org/` | `resource://a/b/c/` (サポートされていないスキーム) | | -| `*://*/*`すべての HTTP, HTTPS, WebSocket URL にマッチ | `http://example.org/` `https://a.org/some/path/` `ws://sockets.somewhere.org/` `wss://ws.example.com/stuff/` | `ftp://ftp.example.org/` (マッチしないスキーム)`ftps://ftp.example.org/` (マッチしないスキーム)`file:///a/` (マッチしないスキーム) | | -| `*://*.mozilla.org/*`"mozilla.org" かそのサブドメインでホストされている HTTP, HTTPS, WebSocket の URL にマッチ | `http://mozilla.org/` `https://mozilla.org/` `http://a.mozilla.org/` `http://a.b.mozilla.org/` `https://b.mozilla.org/path/` `ws://ws.mozilla.org/` `wss://secure.mozilla.org/something` | `ftp://mozilla.org/` (マッチしないスキーム)`http://mozilla.com/` (マッチしないホスト)`http://firefox.org/` (マッチしないホスト) | | -| `*://mozilla.org/`HTTP や HTTPS や WebSocket の"mozilla.org/"のホストのみマッチ | `http://mozilla.org/` `https://mozilla.org/` `ws://mozilla.org/` `wss://mozilla.org/` | `ftp://mozilla.org/` (マッチしないスキーム)`http://a.mozilla.org/` (マッチしないホスト)`http://mozilla.org/a` (マッチしないパス) | | -| `ftp://mozilla.org/`"ftp\://mozilla.org/"のみマッチ | `ftp://mozilla.org` | `http://mozilla.org/` (マッチしないスキーム)`ftp://sub.mozilla.org/` (マッチしないホスト)`ftp://mozilla.org/path` (マッチしないパス) | | -| `https://*/path`HTTPS URL で path が "path"のホストのみマッチ | `https://mozilla.org/path` `https://a.mozilla.org/path` `https://something.com/path` | `http://mozilla.org/path` (マッチしないスキーム)`https://mozilla.org/path/` (マッチしないパス)`https://mozilla.org/a` (マッチしないパス)`https://mozilla.org/` (マッチしないパス)`https://mozilla.org/path?foo=1` (URL クエリーストリングによりマッチしないパス) | | -| `https://*/path/`あらゆるホスト上の HTTPS URL で、パスが "path/" で URL にクエリーストリングのないものにマッチ | `https://mozilla.org/path/` `https://a.mozilla.org/path/` `https://something.com/path`/ | `http://mozilla.org/path/` (マッチしないスキーム)`https://mozilla.org/path` (マッチしないパス)`https://mozilla.org/a` (マッチしないパス)`https://mozilla.org/` (マッチしないパス)`https://mozilla.org/path?foo=1` (URL クエリーストリングによりマッチしないパス) | | -| `https://mozilla.org/*`HTTPS URL のみにマッチで、"mozilla.org"だけ、パスやクエリーストリングは問わない | `https://mozilla.org/` `https://mozilla.org/path` `https://mozilla.org/another` `https://mozilla.org/path/to/doc` `https://mozilla.org/path/to/doc?foo=1` | `http://mozilla.org/path` (マッチしないスキーム)`https://mozilla.com/path` (マッチしないホスト) | | -| `https://mozilla.org/a/b/c/`この URL 、あるいはフラグメント付きのこの URL にのみマッチ | `https://mozilla.org/a/b/c/` `https://mozilla.org/a/b/c/#section1` | これ以外のすべて | | +| `*://*/*`すべての HTTP, HTTPS, WebSocket URL にマッチ | `http://example.org/` `https://a.org/some/path/` `ws://sockets.somewhere.org/` `wss://ws.example.com/stuff/` | `ftp://ftp.example.org/` (マッチしないスキーム)`ftps://ftp.example.org/` (マッチしないスキーム)`file:///a/` (マッチしないスキーム) | | +| `*://*.mozilla.org/*`"mozilla.org" かそのサブドメインでホストされている HTTP, HTTPS, WebSocket の URL にマッチ | `http://mozilla.org/` `https://mozilla.org/` `http://a.mozilla.org/` `http://a.b.mozilla.org/` `https://b.mozilla.org/path/` `ws://ws.mozilla.org/` `wss://secure.mozilla.org/something` | `ftp://mozilla.org/` (マッチしないスキーム)`http://mozilla.com/` (マッチしないホスト)`http://firefox.org/` (マッチしないホスト) | | +| `*://mozilla.org/`HTTP や HTTPS や WebSocket の"mozilla.org/"のホストのみマッチ | `http://mozilla.org/` `https://mozilla.org/` `ws://mozilla.org/` `wss://mozilla.org/` | `ftp://mozilla.org/` (マッチしないスキーム)`http://a.mozilla.org/` (マッチしないホスト)`http://mozilla.org/a` (マッチしないパス) | | +| `ftp://mozilla.org/`"ftp\://mozilla.org/"のみマッチ | `ftp://mozilla.org` | `http://mozilla.org/` (マッチしないスキーム)`ftp://sub.mozilla.org/` (マッチしないホスト)`ftp://mozilla.org/path` (マッチしないパス) | | +| `https://*/path`HTTPS URL で path が "path"のホストのみマッチ | `https://mozilla.org/path` `https://a.mozilla.org/path` `https://something.com/path` | `http://mozilla.org/path` (マッチしないスキーム)`https://mozilla.org/path/` (マッチしないパス)`https://mozilla.org/a` (マッチしないパス)`https://mozilla.org/` (マッチしないパス)`https://mozilla.org/path?foo=1` (URL クエリーストリングによりマッチしないパス) | | +| `https://*/path/`あらゆるホスト上の HTTPS URL で、パスが "path/" で URL にクエリーストリングのないものにマッチ | `https://mozilla.org/path/` `https://a.mozilla.org/path/` `https://something.com/path`/ | `http://mozilla.org/path/` (マッチしないスキーム)`https://mozilla.org/path` (マッチしないパス)`https://mozilla.org/a` (マッチしないパス)`https://mozilla.org/` (マッチしないパス)`https://mozilla.org/path?foo=1` (URL クエリーストリングによりマッチしないパス) | | +| `https://mozilla.org/*`HTTPS URL のみにマッチで、"mozilla.org"だけ、パスやクエリーストリングは問わない | `https://mozilla.org/` `https://mozilla.org/path` `https://mozilla.org/another` `https://mozilla.org/path/to/doc` `https://mozilla.org/path/to/doc?foo=1` | `http://mozilla.org/path` (マッチしないスキーム)`https://mozilla.com/path` (マッチしないホスト) | | +| `https://mozilla.org/a/b/c/`この URL 、あるいはフラグメント付きのこの URL にのみマッチ | `https://mozilla.org/a/b/c/` `https://mozilla.org/a/b/c/#section1` | これ以外のすべて | | | `https://mozilla.org/*/b/*/`"mozilla.org"でホストされた HTTPS URL で、パスは中間のどこかに "b" を含むもの。クエリーストリングが / で終了していればそれにもマッチ | `https://mozilla.org/a/b/c/` `https://mozilla.org/d/b/f/` `https://mozilla.org/a/b/c/d/` `https://mozilla.org/a/b/c/d/#section1` `https://mozilla.org/a/b/c/d/?foo=/` `https://mozilla.org/a?foo=21314&bar=/b/&extra=c/` | `https://mozilla.org/b/*/` (マッチしないパス)`https://mozilla.org/a/b/` (マッチしないパス)`https://mozilla.org/a/b/c/d/?foo=bar` (URL クエリーストリングによりマッチしないパス) | | -| `file:///blah/*`FILE URL でパスが "blah" で始まるもの | `file:///blah/` `file://blah/bleh` | `file:///bleh/` (マッチしないパス) | | +| `file:///blah/*`FILE URL でパスが "blah" で始まるもの | `file:///blah/` `file://blah/bleh` | `file:///bleh/` (マッチしないパス) | | ### 無効なマッチパターン diff --git a/files/ja/mozilla/add-ons/webextensions/modify_a_web_page/index.md b/files/ja/mozilla/add-ons/webextensions/modify_a_web_page/index.md index fac7e118d1fc88..d1a2c7ad5031cc 100644 --- a/files/ja/mozilla/add-ons/webextensions/modify_a_web_page/index.md +++ b/files/ja/mozilla/add-ons/webextensions/modify_a_web_page/index.md @@ -26,7 +26,6 @@ WebExtensions API での実現方法は2つあります: ```json { - "manifest_version": 2, "name": "modify-page", "version": "1.0", @@ -37,7 +36,6 @@ WebExtensions API での実現方法は2つあります: "js": ["page-eater.js"] } ] - } ``` @@ -52,7 +50,7 @@ WebExtensions API での実現方法は2つあります: ```js document.body.textContent = ""; -var header = document.createElement('h1'); +var header = document.createElement("h1"); header.textContent = "This page has been eaten"; document.body.appendChild(header); ``` @@ -71,20 +69,15 @@ document.body.appendChild(header); ```json { - "manifest_version": 2, "name": "modify-page", "version": "1.0", - "permissions": [ - "activeTab", - "contextMenus" - ], + "permissions": ["activeTab", "contextMenus"], "background": { "scripts": ["background.js"] } - } ``` @@ -98,13 +91,13 @@ document.body.appendChild(header); ```js browser.contextMenus.create({ id: "eat-page", - title: "Eat this page" + title: "Eat this page", }); -browser.contextMenus.onClicked.addListener(function(info, tab) { +browser.contextMenus.onClicked.addListener(function (info, tab) { if (info.menuItemId == "eat-page") { browser.tabs.executeScript({ - file: "page-eater.js" + file: "page-eater.js", }); } }); @@ -114,7 +107,7 @@ browser.contextMenus.onClicked.addListener(function(info, tab) { この時点で拡張機能は以下のようになっています。 -```html +```plain modify-page/ background.js manifest.json @@ -145,27 +138,27 @@ modify-page/ ```js browser.contextMenus.create({ id: "eat-page", - title: "Eat this page" + title: "Eat this page", }); function messageTab(tabs) { browser.tabs.sendMessage(tabs[0].id, { - replacement: "Message from the extension!" + replacement: "Message from the extension!", }); } function onExecuted(result) { - var querying = browser.tabs.query({ - active: true, - currentWindow: true - }); - querying.then(messageTab); + var querying = browser.tabs.query({ + active: true, + currentWindow: true, + }); + querying.then(messageTab); } -browser.contextMenus.onClicked.addListener(function(info, tab) { +browser.contextMenus.onClicked.addListener(function (info, tab) { if (info.menuItemId == "eat-page") { let executing = browser.tabs.executeScript({ - file: "page-eater.js" + file: "page-eater.js", }); executing.then(onExecuted); } @@ -179,7 +172,7 @@ browser.contextMenus.onClicked.addListener(function(info, tab) { ```js function eatPageReceiver(request, sender, sendResponse) { document.body.textContent = ""; - var header = document.createElement('h1'); + var header = document.createElement("h1"); header.textContent = request.replacement; document.body.appendChild(header); } @@ -198,7 +191,7 @@ browser.runtime.onMessage.addListener(eatPageReceiver); ```js browser.runtime.sendMessage({ - title: "from page-eater.js" + title: "from page-eater.js", }); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/native_manifests/index.md b/files/ja/mozilla/add-ons/webextensions/native_manifests/index.md index ccbf390d235b15..15c20a898d116c 100644 --- a/files/ja/mozilla/add-ons/webextensions/native_manifests/index.md +++ b/files/ja/mozilla/add-ons/webextensions/native_manifests/index.md @@ -11,8 +11,8 @@ slug: Mozilla/Add-ons/WebExtensions/Native_manifests | [Native messaging マニフェスト](#Native_messaging_manifests) | [native messaging](/ja/docs/Mozilla/Add-ons/WebExtensions/Native_messaging) と呼ぶ機能を可能にします、ここでは拡張機能は端末にインストールされたネイティブアプリとやりとりできます。 | | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Managed storage マニフェスト](#Managed_storage_manifests) | {{WebExtAPIRef("storage.managed")}} API 使って拡張機能がアクセスする読み込み専用データを定義します。 | -| [PKCS #11 マニフェスト](#PKCS_11_manifests) | 拡張機能が {{WebExtAPIRef("pkcs11")}} API を使って PKCS #11 セキュリティモジュールを列挙して、Firefox にインストールできるようにします。 | +| [Managed storage マニフェスト](#Managed_storage_manifests) | {{WebExtAPIRef("storage.managed")}} API 使って拡張機能がアクセスする読み込み専用データを定義します。 | +| [PKCS #11 マニフェスト](#PKCS_11_manifests) | 拡張機能が {{WebExtAPIRef("pkcs11")}} API を使って PKCS #11 セキュリティモジュールを列挙して、Firefox にインストールできるようにします。 | すべてのネイティブマニフェスト用に、ブラウザーがマニフェストを見つけられるように調整する必要があります。 [マニフェストの場所](#Manifest_location) のセクションでこのルールを述べています。 @@ -20,13 +20,13 @@ slug: Mozilla/Add-ons/WebExtensions/Native_manifests native messaging マニフェストは以下のプロパティを含む単一の JSON オブジェクトです: -| 名前 | 種類 | 説明 | -| -------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 名前 | 種類 | 説明 | +| -------------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | String | ネイティブアプリケーションの名前です。この名前は拡張機能の {{WebExtAPIRef("runtime.connectNative()")}} か {{WebExtAPIRef("runtime.sendNativeMessage()")}} に渡される名前と一致している必要があります。OS X と Linux では、native messaging マニフェストの(.json 拡張子を除いた)ファイル名とも一致していなければなりません。Windows では、native messaging マニフェストの場所を記した作成済みレジストリキーの名前と一致している必要があります。次の正規表現にマッチする必要があります: "^\w+(\\.\w+)\*$" つまり、名前には(大文字か小文字の)英数字とアンダースコア、ドットのみ含めることができます。最初または最後の文字にドットを使用することはできず、ドットを 2 つ以上連続させることもできません。 | -| `description` | String | ネイティブアプリケーションの説明です。 | -| `path` | String | ネイティブアプリケーションのパスです。Windows では、マニフェスト自身からの相対パスを指定することもできます。OS X や Linux では絶対パスでなければなりません。 | -| `type` | String | 拡張機能にアプリケーションが接続するために使用する方法を記述します。現在のところ、"stdio" のみが指定可能です。これはアプリケーションが標準入力 (stdin) を介してメッセージを受信し、標準出力 (stdout) を使用してメッセージを送信することを示します。 | -| `allowed_extensions` | Array of String | [Add-on ID](/ja/docs/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID) の配列です。配列中のそれぞれの値はこのネイティブアプリケーションとの通信が許可されている拡張機能を表します。つまり、作成する拡張機能の manifest.json ファイルに [applications](/ja/Add-ons/WebExtensions/manifest.json/applications) キーを含めたくなるものと思われるため、開発中に明示的な ID を設定しておくと良いでしょう。 | +| `description` | String | ネイティブアプリケーションの説明です。 | +| `path` | String | ネイティブアプリケーションのパスです。Windows では、マニフェスト自身からの相対パスを指定することもできます。OS X や Linux では絶対パスでなければなりません。 | +| `type` | String | 拡張機能にアプリケーションが接続するために使用する方法を記述します。現在のところ、"stdio" のみが指定可能です。これはアプリケーションが標準入力 (stdin) を介してメッセージを受信し、標準出力 (stdout) を使用してメッセージを送信することを示します。 | +| `allowed_extensions` | Array of String | [Add-on ID](/ja/docs/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID) の配列です。配列中のそれぞれの値はこのネイティブアプリケーションとの通信が許可されている拡張機能を表します。つまり、作成する拡張機能の manifest.json ファイルに [applications](/ja/Add-ons/WebExtensions/manifest.json/applications) キーを含めたくなるものと思われるため、開発中に明示的な ID を設定しておくと良いでしょう。 | 例として、"ping_pong" ネイティブアプリケーションのマニフェストを以下に示します: @@ -36,7 +36,7 @@ native messaging マニフェストは以下のプロパティを含む単一の "description": "Example host for native messaging", "path": "/path/to/native-messaging/app/ping_pong.py", "type": "stdio", - "allowed_extensions": [ "ping_pong@example.org" ] + "allowed_extensions": ["ping_pong@example.org"] } ``` @@ -60,8 +60,7 @@ managed storage マニフェストには次のプロパティを含む単一の "name": "favourite-colour-examples@mozilla.org", "description": "ignored", "type": "storage", - "data": - { + "data": { "colour": "management thinks it should be blue!" } } @@ -70,7 +69,7 @@ managed storage マニフェストには次のプロパティを含む単一の この JSON マニフェストでは、"favourite-colour-examples\@mozilla.org" 拡張機能は次のようなコードを使ってデータにアクセスできます: ```js -var storageItem = browser.storage.managed.get('colour'); +var storageItem = browser.storage.managed.get("colour"); storageItem.then((res) => { console.log(`Managed colour is: ${res.colour}`); }); diff --git a/files/ja/mozilla/add-ons/webextensions/native_messaging/index.md b/files/ja/mozilla/add-ons/webextensions/native_messaging/index.md index c3f18b3eb24ce1..df7a9dc4fde8c5 100644 --- a/files/ja/mozilla/add-ons/webextensions/native_messaging/index.md +++ b/files/ja/mozilla/add-ons/webextensions/native_messaging/index.md @@ -39,7 +39,6 @@ GitHub の "webextensions-examples" リポジトリーの ["`native-messaging`" ```json { - "description": "Native messaging example add-on", "manifest_version": 2, "name": "Native messaging example", @@ -64,7 +63,6 @@ GitHub の "webextensions-examples" リポジトリーの ["`native-messaging`" }, "permissions": ["nativeMessaging"] - } ``` @@ -88,7 +86,7 @@ GitHub の "webextensions-examples" リポジトリーの ["`native-messaging`" "description": "Example host for native messaging", "path": "/path/to/native-messaging/app/ping_pong.py", "type": "stdio", - "allowed_extensions": [ "ping_pong@example.org" ] + "allowed_extensions": ["ping_pong@example.org"] } ``` @@ -110,7 +108,7 @@ GitHub の "webextensions-examples" リポジトリーの ["`native-messaging`" "description": "Example host for native messaging", "path": "c:\\path\\to\\native-messaging\\app\\ping_pong_win.bat", "type": "stdio", - "allowed_extensions": [ "ping_pong@example.org" ] + "allowed_extensions": ["ping_pong@example.org"] } ``` @@ -223,9 +221,7 @@ On a click on the browser action, send the app a message. */ browser.browserAction.onClicked.addListener(() => { console.log("Sending: ping"); - let sending = browser.runtime.sendNativeMessage( - "ping_pong", - "ping"); + let sending = browser.runtime.sendNativeMessage("ping_pong", "ping"); sending.then(onResponse, onError); }); ``` @@ -244,62 +240,60 @@ browser.browserAction.onClicked.addListener(() => { #!/usr/local/bin/node (() => { + let payloadSize = null; + + // A queue to store the chunks as we read them from stdin. + // This queue can be flushed when `payloadSize` data has been read + let chunks = []; + + // Only read the size once for each payload + const sizeHasBeenRead = () => Boolean(payloadSize); + + // All the data has been read, reset everything for the next message + const flushChunksQueue = () => { + payloadSize = null; + chunks.splice(0); + }; + + const processData = () => { + // Create one big buffer with all the chunks + const stringData = Buffer.concat(chunks); + + // The browser will emit the size as a header of the payload, + // if it hasn't been read yet, do it. + // The next time we'll need to read the payload size is when all of the data + // of the current payload has been read (ie. data.length >= payloadSize + 4) + if (!sizeHasBeenRead()) { + payloadSize = stringData.readUInt32LE(0); + } + + // If the data we have read so far is >= to the size advertised in the header, + // it means we have all of the data sent. + // We add 4 here because that's the size of the bytes that old the payloadSize + if (stringData.length >= payloadSize + 4) { + // Remove the header + const contentWithoutSize = stringData.slice(4, payloadSize + 4); + + // Reset the read size and the queued chunks + flushChunksQueue(); + + const json = JSON.parse(contentWithoutSize); + // Do something with the data… + } + }; + + process.stdin.on("readable", () => { + // A temporary variable holding the nodejs.Buffer of each + // chunk of data read off stdin + let chunk = null; + + // Read all of the available data + while ((chunk = process.stdin.read()) !== null) { + chunks.push(chunk); + } - let payloadSize = null; - - // A queue to store the chunks as we read them from stdin. - // This queue can be flushed when `payloadSize` data has been read - let chunks = []; - - // Only read the size once for each payload - const sizeHasBeenRead = () => Boolean(payloadSize); - - // All the data has been read, reset everything for the next message - const flushChunksQueue = () => { - payloadSize = null; - chunks.splice(0); - }; - - const processData = () => { - // Create one big buffer with all the chunks - const stringData = Buffer.concat(chunks); - - // The browser will emit the size as a header of the payload, - // if it hasn't been read yet, do it. - // The next time we'll need to read the payload size is when all of the data - // of the current payload has been read (ie. data.length >= payloadSize + 4) - if (!sizeHasBeenRead()) { - payloadSize = stringData.readUInt32LE(0); - } - - // If the data we have read so far is >= to the size advertised in the header, - // it means we have all of the data sent. - // We add 4 here because that's the size of the bytes that old the payloadSize - if (stringData.length >= (payloadSize + 4)) { - // Remove the header - const contentWithoutSize = stringData.slice(4, (payloadSize + 4)); - - // Reset the read size and the queued chunks - flushChunksQueue(); - - const json = JSON.parse(contentWithoutSize); - // Do something with the data… - } - }; - - process.stdin.on('readable', () => { - // A temporary variable holding the nodejs.Buffer of each - // chunk of data read off stdin - let chunk = null; - - // Read all of the available data - while ((chunk = process.stdin.read()) !== null) { - chunks.push(chunk); - } - - processData(); - - }); + processData(); + }); })(); ``` @@ -394,7 +388,7 @@ while True: ネイティブアプリケーションを閉じるためには、次のようにします。 - OS X や Linux のような \*nix システムでは、ブラウザーはネイティブアプリケーションが正しく終了する機会を与えるために SIGTERM を送信し、その後 SIGKILL を送信します。これらのシグナルは新しいプロセスグループを作成して分けない限りすべてのサブプロセスに伝播します。 -- Windows では、ブラウザーはネイティブアプリケーションのプロセスを [Job オブジェクト](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684161(v=vs.85).aspx)とし、ジョブを kill します。 ネイティブアプリケーションが追加でプロセスを立ち上げ、アプリケーション自体が kill された後もそのままにしたい場合、ネイティブアプリケーションは追加のプロセスを [`CREATE_BREAKAWAY_FROM_JOB`]() フラグを立てて立ち上げる必要があります。 +- Windows では、ブラウザーはネイティブアプリケーションのプロセスを [Job オブジェクト]()とし、ジョブを kill します。 ネイティブアプリケーションが追加でプロセスを立ち上げ、アプリケーション自体が kill された後もそのままにしたい場合、ネイティブアプリケーションは追加のプロセスを [`CREATE_BREAKAWAY_FROM_JOB`]() フラグを立てて立ち上げる必要があります。 ## トラブルシューティング diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md index 5f8319e6a7e819..005fca1f548070 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.md @@ -26,11 +26,14 @@ slug: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items 次に、拡張機能のバックグラウンドスクリプト内にコンテキストメニューを追加(および更新、削除)することもできます。メニュー項目を作成するには id、タイトル、表示するコンテキストメニューを指定します。 ```js -browser.contextMenus.create({ - id: "log-selection", - title: browser.i18n.getMessage("contextMenuItemSelectionLogger"), - contexts: ["selection"] -}, onCreated); +browser.contextMenus.create( + { + id: "log-selection", + title: browser.i18n.getMessage("contextMenuItemSelectionLogger"), + contexts: ["selection"], + }, + onCreated, +); ``` そして、拡張機能はメニュー項目がクリックされるのを待ち受けします。クリックされた項目、クリックされたコンテキスト、クリックされたタブの詳細に関する渡された情報は、適切な拡張機能を呼び出すために使用されます。 diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md index 21983f79030bf6..50f02196b155fb 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.md @@ -40,14 +40,16 @@ function handleHidden() { console.log("panel is being hidden"); } -browser.devtools.panels.create( - "My Panel", // title - "icons/star.png", // icon - "devtools/panel/panel.html" // content -).then((newPanel) => { - newPanel.onShown.addListener(handleShown); - newPanel.onHidden.addListener(handleHidden); -}); +browser.devtools.panels + .create( + "My Panel", // title + "icons/star.png", // icon + "devtools/panel/panel.html", // content + ) + .then((newPanel) => { + newPanel.onShown.addListener(handleShown); + newPanel.onHidden.addListener(handleHidden); + }); ``` 拡張機能はインスペクターウィンドウの中で [`devtools.inspectedWindow.eval()`](/ja/docs/Mozilla/Add-ons/WebExtensions/API/devtools/inspectedWindow/eval) を使うか、バックグラウンドスクリプトからメッセージを渡してコンテンツスクリプトに挿入することで、コードを実行することができます。この方法のより詳しくは[開発ツールの拡張](/ja/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools)を参照してください。 diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/extension_pages/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/extension_pages/index.md index 666418db6fd6c0..38da7d8e10a4d3 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/extension_pages/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/extension_pages/index.md @@ -35,7 +35,7 @@ let createData = { type: "detached_panel", url: "panel.html", width: 250, - height: 100 + height: 100, }; let creating = browser.windows.create(createData); ``` @@ -45,7 +45,7 @@ let creating = browser.windows.create(createData); 例えば、以下の例では、ユーザーがボタンをクリックしたときに {{WebExtAPIRef("windows.remove()")}} にウィンドウ の ID を渡しています。 ```js -document.getElementById("closeme").addEventListener("click", function(){ +document.getElementById("closeme").addEventListener("click", function () { let winId = browser.windows.WINDOW_ID_CURRENT; let removing = browser.windows.remove(winId); }); @@ -58,7 +58,7 @@ document.getElementById("closeme").addEventListener("click", function(){ ```js function onVisited(historyItem) { if (historyItem.url == browser.extension.getURL(myPage)) { - browser.history.deleteUrl({url: historyItem.url}); + browser.history.deleteUrl({ url: historyItem.url }); } } diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/notifications/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/notifications/index.md index f16001cadbcd5a..f9def9e7f6588a 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/notifications/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/notifications/index.md @@ -25,10 +25,10 @@ slug: Mozilla/Add-ons/WebExtensions/user_interface/Notifications let title = browser.i18n.getMessage("notificationTitle"); let content = browser.i18n.getMessage("notificationContent", message.url); browser.notifications.create({ - "type": "basic", - "iconUrl": browser.extension.getURL("icons/link-48.png"), - "title": title, - "message": content + type: "basic", + iconUrl: browser.extension.getURL("icons/link-48.png"), + title: title, + message: content, }); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/options_pages/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/options_pages/index.md index e867291e857df5..97b89abe241922 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/options_pages/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/options_pages/index.md @@ -20,17 +20,17 @@ slug: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages オプションページを作成するには、ページを定義する HTML を書きます。このページは通常のページと同様に、 CSS と JavaScript ファイルを入れることができます。このページは、 [favourite-color](https://github.com/mdn/webextensions-examples/tree/master/favourite-colour) の例から取ってきていて、 JavaScript ファイルが含まれています。 ```html - + - +
- + diff --git a/files/ja/mozilla/add-ons/webextensions/user_interface/sidebars/index.md b/files/ja/mozilla/add-ons/webextensions/user_interface/sidebars/index.md index 480265d6f0e78c..33fa4f04116ceb 100644 --- a/files/ja/mozilla/add-ons/webextensions/user_interface/sidebars/index.md +++ b/files/ja/mozilla/add-ons/webextensions/user_interface/sidebars/index.md @@ -21,7 +21,7 @@ slug: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars ```js // sidebar.js -browser.windows.getCurrent({populate: true}).then((windowInfo) => { +browser.windows.getCurrent({ populate: true }).then((windowInfo) => { myWindowId = windowInfo.id; }); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/work_with_the_bookmarks_api/index.md b/files/ja/mozilla/add-ons/webextensions/work_with_the_bookmarks_api/index.md index fbf8f6860f1f37..2b7cc633fb3360 100644 --- a/files/ja/mozilla/add-ons/webextensions/work_with_the_bookmarks_api/index.md +++ b/files/ja/mozilla/add-ons/webextensions/work_with_the_bookmarks_api/index.md @@ -114,8 +114,11 @@ Bookmarks API の使い方を理解するため、[bookmark-it](https://github.c 他のバックグラウンドスクリプトと同様に、[background.js](https://github.com/mdn/webextensions-examples/blob/master/bookmark-it/background.js) は拡張機能が開始してすぐに実行されます。最初にスクリプトは `updateActiveTab()` を呼び出し、ここでは {{WebExtAPIRef("tabs.query")}} を使って現在のタブの `Tabs` オブジェクトを取得して開始し、そのオブジェクトを `updatetab()` に渡します、コードは次の通り: ```js - var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true}); - gettingActiveTab.then(updateTab); +var gettingActiveTab = browser.tabs.query({ + active: true, + currentWindow: true, +}); +gettingActiveTab.then(updateTab); ``` `updatetab()` は 最初にアクティブなタブの URL を `isSupportedProtocol()` に渡します: @@ -130,12 +133,12 @@ Bookmarks API の使い方を理解するため、[bookmark-it](https://github.c `isSupportedProtocol()` はアクティブタブに表示される URL がブックマークできるかを決めます。タブの URL からプロトコルを抽出するために、拡張機能は [HTMLHyperlinkElementUtils](/ja/docs/Web/API/HTMLHyperlinkElementUtils) を利用して `` 要素にタブの URL を追加してから、`protocol` プロパティを使ってプロトコルを取得します。 ```js - function isSupportedProtocol(urlString) { - var supportedProtocols = ["https:", "http:", "ftp:", "file:"]; - var url = document.createElement('a'); - url.href = urlString; - return supportedProtocols.indexOf(url.protocol) != -1; - } +function isSupportedProtocol(urlString) { + var supportedProtocols = ["https:", "http:", "ftp:", "file:"]; + var url = document.createElement("a"); + url.href = urlString; + return supportedProtocols.indexOf(url.protocol) != -1; +} ``` ブックマークがプロトコルをサポートしている場合、拡張機能はタブの URL がブックマーク済みかどうかを決めて、その場合に `updateIcon()` を呼び出します: @@ -152,19 +155,21 @@ Bookmarks API の使い方を理解するため、[bookmark-it](https://github.c ```js function updateIcon() { browser.browserAction.setIcon({ - path: currentBookmark ? { - 19: "icons/star-filled-19.png", - 38: "icons/star-filled-38.png" - } : { - 19: "icons/star-empty-19.png", - 38: "icons/star-empty-38.png" - }, - tabId: currentTab.id + path: currentBookmark + ? { + 19: "icons/star-filled-19.png", + 38: "icons/star-filled-38.png", + } + : { + 19: "icons/star-empty-19.png", + 38: "icons/star-empty-38.png", + }, + tabId: currentTab.id, }); browser.browserAction.setTitle({ // Screen readers can see the title - title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!', - tabId: currentTab.id + title: currentBookmark ? "Unbookmark it!" : "Bookmark it!", + tabId: currentTab.id, }); } ``` @@ -182,7 +187,7 @@ function toggleBookmark() { if (currentBookmark) { browser.bookmarks.remove(currentBookmark.id); } else { - browser.bookmarks.create({title: currentTab.title, url: currentTab.url}); + browser.bookmarks.create({ title: currentTab.title, url: currentTab.url }); } } ``` diff --git a/files/ja/mozilla/add-ons/webextensions/working_with_files/index.md b/files/ja/mozilla/add-ons/webextensions/working_with_files/index.md index eb32172a12b34b..4caafc72372307 100644 --- a/files/ja/mozilla/add-ons/webextensions/working_with_files/index.md +++ b/files/ja/mozilla/add-ons/webextensions/working_with_files/index.md @@ -20,7 +20,7 @@ slug: Mozilla/Add-ons/WebExtensions/Working_with_files この仕組みでは、あなたのウェブサイト(や URL で決められたあらゆる場所)からユーザーのコンピューターにファイルを入手できます。主要なメソッドは {{WebExtAPIRef("downloads.download()")}} で、その簡単なフォームで URL を受け付けて、その URL からユーザーの既定のダウンロードフォルダーにファイルをダウンロードします: ```js -browser.downloads.download({url: "https://example.org/image.png"}) +browser.downloads.download({ url: "https://example.org/image.png" }); ``` ユーザーが `saveAs` パラメーターで指定した場所にダウンロードさせることもできます。 @@ -78,11 +78,11 @@ Store Collected Images の例では、画像コンテキストメニューを使 ```js async function saveCollectedBlobs(collectionName, collectedBlobs) { - const storedImages = await getFileStorage({name: "stored-images"}); + const storedImages = await getFileStorage({ name: "stored-images" }); - for (const item of collectedBlobs) { + for (const item of collectedBlobs) { await storedImages.put(`${collectionName}/${item.uuid}`, item.blob); - } + } } ``` @@ -92,15 +92,15 @@ async function saveCollectedBlobs(collectionName, collectedBlobs) { ```js export async function loadStoredImages(filter) { - const imagesStore = await getFileStorage({name: "stored-images"}); - let listOptions = filter ? {includes: filter} : undefined; - const imagesList = await imagesStore.list(listOptions); - let storedImages = []; - for (const storedName of imagesList) { + const imagesStore = await getFileStorage({ name: "stored-images" }); + let listOptions = filter ? { includes: filter } : undefined; + const imagesList = await imagesStore.list(listOptions); + let storedImages = []; + for (const storedName of imagesList) { const blob = await imagesStore.get(storedName); - storedImages.push({storedName, blobUrl: URL.createObjectURL(blob)}); - } - return storedImages; + storedImages.push({ storedName, blobUrl: URL.createObjectURL(blob) }); + } + return storedImages; } ``` @@ -112,11 +112,11 @@ Note the use of [URL.createObjectURL(blob)](/ja/docs/Web/API/URL/createObjectURL ```js async function removeStoredImages(storedImages) { - const imagesStore = await getFileStorage({name: "stored-images"}); - for (const storedImage of storedImages) { + const imagesStore = await getFileStorage({ name: "stored-images" }); + for (const storedImage of storedImages) { URL.revokeObjectURL(storedImage.blobUrl); await imagesStore.remove(storedImage.storedName); - } + } } ``` diff --git a/files/ja/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md b/files/ja/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md index 7d269d452416ae..fe460eba09a335 100644 --- a/files/ja/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md +++ b/files/ja/mozilla/add-ons/webextensions/working_with_the_tabs_api/index.md @@ -71,9 +71,7 @@ Tabs API 機能の大半では権限は不要ですが、次の例外はあり "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/tabs-tabs-tabs", "manifest_version": 2, "name": "Tabs, tabs, tabs", - "permissions": [ - "tabs" - ], + "permissions": ["tabs"], "version": "1.0" } ``` @@ -88,43 +86,35 @@ Tabs API 機能の大半では権限は不要ですが、次の例外はあり tabs.html では拡張機能のポップアップのコンテンツを定義します。 ```html - + + + + + - - - - + +
+
+
Tabs-tabs-tabs
+
- +
Move active tab to the beginning of the window
-
-
-
Tabs-tabs-tabs
-
- - Move active tab to the beginning of the window
- - -… - -Define the other menu items -… - -
+ … Define the other menu items … -

Switch to tab

- -
+
+

Switch to tab

+
+
-
- - - - + + ``` @@ -150,7 +140,7 @@ document.addEventListener("DOMContentLoaded", listTabs); ```js function getCurrentWindowTabs() { - return browser.tabs.query({currentWindow: true}); + return browser.tabs.query({ currentWindow: true }); } ``` @@ -179,24 +169,23 @@ function listTabs() { 1. {{WebExtAPIRef("tabs.Tab")}} オブジェクトからの最初の 5 項目でループする。 2. 各項目ごとに、文書のフラグメントのハイパーリンクを追加する。 - - リンクのラベル—つまり、そのテキスト—が、タブのタイトル (ない場合はその ID)を使って、セットされる - - タブの ID を使ってリンクのアドレスがセットされる。 + - リンクのラベル—つまり、そのテキスト—が、タブのタイトル (ない場合はその ID)を使って、セットされる + - タブの ID を使ってリンクのアドレスがセットされる。 ```js - for (let tab of tabs) { - if (!tab.active && counter <= limit) { - let tabLink = document.createElement('a'); +for (let tab of tabs) { + if (!tab.active && counter <= limit) { + let tabLink = document.createElement("a"); - tabLink.textContent = tab.title || tab.id; + tabLink.textContent = tab.title || tab.id; - tabLink.setAttribute('href', tab.id); - tabLink.classList.add('switch-tabs'); - currentTabs.appendChild(tabLink); - } - - counter += 1; + tabLink.setAttribute("href", tab.id); + tabLink.classList.add("switch-tabs"); + currentTabs.appendChild(tabLink); + } - } + counter += 1; +} ``` 最後に、`tabs-list` div に文書のフラグメントが書き込まれる: @@ -282,16 +271,18 @@ None of the functions require a permission to operate, so there are no features tabs.html defines the "menu" displayed in the popup, which includes the "Move active tab to the beginning of the window list" option, with a series of `` tags grouped by a visual separator. Each menu item is given an ID, which is used in tabs.js to determine which menu item is being requested. ```html - Move active tab to the beginning of the window
- Move active tab to the end of the window
- -
+Move active tab to the beginning of the window
+Move active tab to the end of the window
+
- Duplicate active tab
+Duplicate active tab
- Reload active tab
- Alert active tab info
+Reload active tab
+Alert active tab info
``` #### [tabs.js](https://github.com/mdn/webextensions-examples/blob/master/tabs-tabs-tabs/tabs.js) @@ -318,16 +309,16 @@ A series of `if` statements then look to match the ID of the item clicked. This code snippet is for the "Move active tab to the beginning of the window list" option: ```js - if (e.target.id === "tabs-move-beginning") { - callOnActiveTab((tab, tabs) => { - var index = 0; - if (!tab.pinned) { - index = firstUnpinnedTab(tabs); - } - console.log(`moving ${tab.id} to ${index}`) - browser.tabs.move([tab.id], {index}); - }); - } +if (e.target.id === "tabs-move-beginning") { + callOnActiveTab((tab, tabs) => { + var index = 0; + if (!tab.pinned) { + index = firstUnpinnedTab(tabs); + } + console.log(`moving ${tab.id} to ${index}`); + browser.tabs.move([tab.id], { index }); + }); +} ``` It's worth noting the use of `console.log()`. This enables you to output information to the [debugger](/ja/docs/Mozilla/Add-ons/WebExtensions/Debugging) console, which can be useful when resolving issues found during development. @@ -337,15 +328,15 @@ It's worth noting the use of `console.log()`. This enables you to output informa The move code first calls `callOnActiveTab()` which in turn calls `getCurrentWindowTabs()` to get a {{WebExtAPIRef("tabs.Tab")}} object containing the active window's tabs. It then loops through the object to find and return the active tab object: ```js - function callOnActiveTab(callback) { - getCurrentWindowTabs().then((tabs) => { - for (var tab of tabs) { - if (tab.active) { - callback(tab, tabs); - } - } - }); - } +function callOnActiveTab(callback) { + getCurrentWindowTabs().then((tabs) => { + for (var tab of tabs) { + if (tab.active) { + callback(tab, tabs); + } + } + }); +} ``` ##### ピン止めされたタブ @@ -354,18 +345,18 @@ A feature of tabs is that the user can _pin_ tabs in a window. Pinned tabs are p ```js function firstUnpinnedTab(tabs) { - for (var tab of tabs) { - if (!tab.pinned) { - return tab.index; - } - } + for (var tab of tabs) { + if (!tab.pinned) { + return tab.index; + } + } } ``` We now have everything needed to move the tab: the active tab object from which we can get the tab ID and the position the tab is to be moved to. So, we can implement the move: ```js - browser.tabs.move([tab.id], {index}); +browser.tabs.move([tab.id], { index }); ``` The remaining functions to duplicate, reload, create, and remove tabs are implemented similarly. @@ -462,27 +453,21 @@ The latter is the most useful, as it allows an extension to use {{WebExtAPIRef(" { "description": "Adds a page action to toggle applying CSS to pages.", - "manifest_version": 2, - "name": "apply-css", - "version": "1.0", - "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/apply-css", - - "background": { + "manifest_version": 2, + "name": "apply-css", + "version": "1.0", + "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/apply-css", + "background": { "scripts": ["background.js"] - }, - - "page_action": { + }, + "page_action": { "default_icon": "icons/off.svg", "browser_style": true - }, - - "permissions": [ - "activeTab", - "tabs" - ] + }, + "permissions": ["activeTab", "tabs"] } ``` @@ -510,9 +495,9 @@ When first loaded, the extension uses {{WebExtAPIRef("tabs.query")}} to get a li var gettingAllTabs = browser.tabs.query({}); gettingAllTabs.then((tabs) => { - for (let tab of tabs) { - initializePageAction(tab); - } + for (let tab of tabs) { + initializePageAction(tab); + } }); ``` @@ -520,9 +505,9 @@ gettingAllTabs.then((tabs) => { ```js function protocolIsApplicable(url) { - var anchor = document.createElement('a'); - anchor.href = url; - return APPLICABLE_PROTOCOLS.includes(anchor.protocol); + var anchor = document.createElement("a"); + anchor.href = url; + return APPLICABLE_PROTOCOLS.includes(anchor.protocol); } ``` @@ -530,12 +515,11 @@ Then, if the example can act on the tab, `initializePageAction()` sets the tab's ```js function initializePageAction(tab) { - - if (protocolIsApplicable(tab.url)) { - browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"}); - browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY}); - browser.pageAction.show(tab.id); - } + if (protocolIsApplicable(tab.url)) { + browser.pageAction.setIcon({ tabId: tab.id, path: "icons/off.svg" }); + browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY }); + browser.pageAction.show(tab.id); + } } ``` @@ -559,24 +543,21 @@ browser.pageAction.onClicked.addListener(toggleCSS); ```js function toggleCSS(tab) { - - - function gotTitle(title) { - + function gotTitle(title) { if (title === TITLE_APPLY) { - browser.pageAction.setIcon({tabId: tab.id, path: "icons/on.svg"}); - browser.pageAction.setTitle({tabId: tab.id, title: TITLE_REMOVE}); - browser.tabs.insertCSS({code: CSS}); + browser.pageAction.setIcon({ tabId: tab.id, path: "icons/on.svg" }); + browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_REMOVE }); + browser.tabs.insertCSS({ code: CSS }); } else { - browser.pageAction.setIcon({tabId: tab.id, path: "icons/off.svg"}); - browser.pageAction.setTitle({tabId: tab.id, title: TITLE_APPLY}); - browser.tabs.removeCSS({code: CSS}); + browser.pageAction.setIcon({ tabId: tab.id, path: "icons/off.svg" }); + browser.pageAction.setTitle({ tabId: tab.id, title: TITLE_APPLY }); + browser.tabs.removeCSS({ code: CSS }); } - } + } - var gettingTitle = browser.pageAction.getTitle({tabId: tab.id}); + var gettingTitle = browser.pageAction.getTitle({ tabId: tab.id }); - gettingTitle.then(gotTitle); + gettingTitle.then(gotTitle); } ``` @@ -584,7 +565,7 @@ Finally, to ensure that the `pageAction` is valid after each update to the tab, ```js browser.tabs.onUpdated.addListener((id, changeInfo, tab) => { - initializePageAction(tab); + initializePageAction(tab); }); ``` diff --git a/files/ja/mozilla/add-ons/webextensions/your_first_webextension/index.md b/files/ja/mozilla/add-ons/webextensions/your_first_webextension/index.md index 363181aec66e62..bf87472368ecec 100644 --- a/files/ja/mozilla/add-ons/webextensions/your_first_webextension/index.md +++ b/files/ja/mozilla/add-ons/webextensions/your_first_webextension/index.md @@ -26,7 +26,6 @@ cd borderify ```json { - "manifest_version": 2, "name": "Borderify", "version": "1.0", @@ -43,7 +42,6 @@ cd borderify "js": ["borderify.js"] } ] - } ``` diff --git a/files/ja/mozilla/add-ons/webextensions/your_second_webextension/index.md b/files/ja/mozilla/add-ons/webextensions/your_second_webextension/index.md index 84b4a2ccb07ad9..1d052596e268b1 100644 --- a/files/ja/mozilla/add-ons/webextensions/your_second_webextension/index.md +++ b/files/ja/mozilla/add-ons/webextensions/your_second_webextension/index.md @@ -65,9 +65,7 @@ cd beastify "48": "icons/beasts-48.png" }, - "permissions": [ - "activeTab" - ], + "permissions": ["activeTab"], "browser_action": { "default_icon": "icons/beasts-32.png", @@ -141,7 +139,7 @@ touch choose_beast.html choose_beast.css choose_beast.js HTML ファイルは次のようになります。 ```html - + @@ -190,19 +188,19 @@ button { text-align: center; font-size: 1.5em; cursor: pointer; - background-color: #E5F2F2; + background-color: #e5f2f2; } button:hover { - background-color: #CFF2F2; + background-color: #cff2f2; } button[type="reset"] { - background-color: #FBFBC9; + background-color: #fbfbc9; } button[type="reset"]:hover { - background-color: #EAEA9D; + background-color: #eaea9d; } ``` @@ -249,7 +247,7 @@ function listenForClicks() { let url = beastNameToURL(e.target.textContent); browser.tabs.sendMessage(tabs[0].id, { command: "beastify", - beastURL: url + beastURL: url, }); }); }