diff options
Diffstat (limited to 'files/ko/mozilla/add-ons/webextensions')
35 files changed, 4768 insertions, 0 deletions
diff --git a/files/ko/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/ko/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html new file mode 100644 index 0000000000..1b2d52b0cd --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html @@ -0,0 +1,131 @@ +--- +title: Anatomy of an extension +slug: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +--- +<div>{{AddonSidebar}}</div> + +<p>확장앱은 배포 및 설치를 위해 패키징 된 파일 모음으로 구성됩니다. 이 아티클은 확장앱에 있을 수 있는 파일들을 빠르게 살펴봅니다.</p> + +<h2 id="manifest.json">manifest.json</h2> + +<p>manifest.json 파일은 모든 확장앱이 가져야하는 유일한 파일입니다. 이 파일에는 이름, 버전 및 필요한 권한과 같은 메타정보가 들어 있습니다. </p> + +<p>또한 확장앱에 포함될 다른 파일들(하단 목록)을 가리킵니다.</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_scripts">Background pages</a>: (브라우저 창의 수명과 독립적으로) 오랜 시간 실행되는 로직 구현.</li> + <li>확장앱의 아이콘 및 기타 버튼들.</li> + <li><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Sidebars_popups_options_pages">사이드바, 팝업, 옵션 페이지</a>: UI 컴포넌트를 제공하는 HTML 파일들</li> + <li><a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Content_scripts">컨텐츠 스크립트</a>: 웹페이지에 주입할 자바스크립트 파일</li> +</ul> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13669/webextension-anatomy.png" style="display: block; height: 581px; margin-left: auto; margin-right: auto; width: 600px;"></p> + +<p>세부 내용: <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a> 참조.</p> + +<p>manifest에 참조 된 항목 외에도, <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Extension_pages">Extension pages</a>와 해당 페이지의 리소스가 확장앱 번들에 포함될 수 있습니다.</p> + +<h2 id="Background_scripts">Background scripts</h2> + +<p><span class="translation">확장앱은 종종 특정 웹 페이지나 브라우저 창의 수명과 독립적으로 장기간 상태를 유지하거나 작업을 수행해야 합니다. 그때 필요한 것이 </span>백그라운드 스크립트입니다.</p> + +<p>백그라운드 스크립트는 <span class="translation">확장앱이 로드 되자마자 로드되며 확장앱이 다시 비활성화 또는 </span>제거될 때까지<span class="translation"> 로드된 상태를 유지합니다</span>. 적절한 <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions">권한</a>을 요청했다면 이 스크립트에서 <a href="/en-US/Add-ons/WebExtensions/API">WebExtension APIs</a>를 사용할 수 있습니다.</p> + +<h3 id="백그라운드_스크립트_정의">백그라운드 스크립트 정의</h3> + +<p>"manifest.json"에 <code>background</code> 키로 백그라운드 스크립트를 포함할 수 있습니다:</p> + +<pre class="brush: json">// manifest.json + +"background": { + "scripts": ["background-script.js"] +}</pre> + +<p>여러 개의 백그라운드 스크립트를 지정할 수 있습니다: 그 경우 한 웹페이지에서 여러 스크립트들이 실행되듯이 백그라운드 스크립트들이 동일한 context에서 실행됩니다.</p> + +<h3 id="백그라운드_스크립트_환경">백그라운드 스크립트 환경</h3> + +<h4 id="DOM_APIs">DOM APIs</h4> + +<p>백그라운드 스크립트는 background pages라는 특별한 페이지의 context에서 실행됩니다. 이것은 백그라운드 스크립트에 모든 표준 DOM API들을 제공하는 전역 <code><a href="/en-US/docs/Web/API/Window">window</a></code> 객체를 제공합니다.</p> + +<p>background page를 제공할 필요는 없습니다. 백그라운드 스크립트를 추가했다면 빈 background page가 생성됩니다.</p> + +<p>그러나 background page를 별도의 HTML 파일로 제공하도록 선택할 수 있습니다.</p> + +<pre class="brush: json">// manifest.json + +"background": { + "page": "background-page.html" +}</pre> + +<h4 id="WebExtension_APIs">WebExtension APIs</h4> + +<p>백그라운드 스크립트는 선언된 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a> 내의 모든 <a href="/en-US/Add-ons/WebExtensions/API">WebExtension APIs</a>를 사용할 수 있습니다.</p> + +<h4 id="Cross-origin_access">Cross-origin access</h4> + +<p>백그라운드 스크립트는 선언된 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">host 권한</a> 내의 모든 서버(host)에 XHR 요청을 할 수 있습니다.</p> + +<h4 id="Web_content">Web content</h4> + +<p>백그라운드 스크립트는 웹 페이지에 직접 엑세스하지 못합니다. 그러나 웹페이지에 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">컨텐츠 스크립트</a>를 삽입할 수 있으며 <a href="/en-US/Add-ons/WebExtensions/Content_scripts#Communicating_with_background_scripts">메시지 전달 API를 통해 컨텐츠 스크립트와 통신할 수 있습니다</a>.</p> + +<h4 id="Content_security_policy">Content security policy</h4> + +<p>백그라운드 스크립트<span class="translation">는 </span><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a></code><span class="translation"> 사용과 같이</span><span class="translation"> 잠재적으로 위험할 수 있는 특정 작업을 제한합니다.</span> 자세한 내용은 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">컨텐츠 보안 정책</a>을 참조하십시오.</p> + +<h2 id="Sidebars_popups_options_pages">Sidebars, popups, options pages</h2> + +<p>확장앱은 HTML를 이용하여 다양한 UI를 포함할 수 있습니다.</p> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars">사이드바</a>는 <span class="translation">브라우저 창의 왼쪽, 웹 페이지 옆에 표시되는 창입니다.</span></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups">팝업</a>은 사용자가 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action">툴바 버튼</a> 이나 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions">주소창 버튼</a>를 클릭 할 때 표시되는 다이얼로그입니다</li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages">옵션 페이지</a>는 브라우저의 애드온 매니저에서 확장앱의 환경 설정에 접근할 때 표시 되는 페이지입니다.</li> +</ul> + +<p>이러한 각 구성 요소에 대해 HTML 파일을 만들고 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a>의 특정 속성에 지정합니다. 이 HTML 파일은 일반 웹 페이지와 마찬가지로 CSS 및 JavaScript 파일이 포함될 수 있습니다. </p> + +<p><span class="translation">이 페이지들은 모두 </span><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages">Extension pages</a><span class="translation"> 유형이며, 일반 웹 페이지와 달리 </span>이 페이지에서 실행되는<span class="translation"> javaScript는 </span><span class="translation">권한이 부여된 WebExtension API를 모두 사용할 수 있습니다(</span>백그라운드 스크립트<span class="translation">와 동일).</span><br> + {{WebExtAPIRef("runtime.getBackgroundPage()")}}<br> + 심지어 위와 같이 background page에서 사용하는 변수에 직접 접근할 수도 있습니다.</p> + +<h2 id="Extension_pages">Extension pages</h2> + +<p><span class="translation">또한 미리 정의된 UI에 연결되지 않은 HTML 문서를 확장앱에 포함할 수 있습니다. </span>사이드바<span class="translation">, </span>팝업<span class="translation"> 또는 옵션 페이지에 제공할 문서와 달리 manifest.json에 이 페이지를 정의하는 항목은 없습니다. 그러나 이 페이지 또한 </span>백그라운드 스크립트<span class="translation">와 동일하게 권한이 부여된 WebExtension API에 대한 접근 권한을 가집니다.</span></p> + +<p>일반적으로 {{WebExtAPIRef("windows.create()")}} 또는 {{WebExtAPIRef("tabs.create()")}}를 사용하여 Extension page를 로드할 수 있습니다.</p> + +<p>세부 내용 : <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages">Extension pages</a> 참조.</p> + +<h2 id="Content_scripts">Content scripts</h2> + +<p>컨텐츠 스크립트를 사용하여 웹 페이지에 접근하고 수정하십시오. 컨텐츠 스크립트는 <span class="translation">웹 페이지에 로드되고 해당 페이지의 context에서 실행됩니다.</span></p> + +<p>컨텐츠 스크립트<span class="translation">는 웹 페이지의 context에서 실행되는, 확장앱용 스크립트입니다. 이는 페이지 내의 {{HTMLElement ( "script")}} 요소 등 페이지 자체가 로드하는 스크립트와 다릅니다.</span></p> + +<p>컨텐츠 스크립트는 <span class="translation">웹페이지가 로드하는 일반 스크립트처럼 DOM에 접근 및 조작을 할 수 있습니다.</span></p> + +<p><span class="translation">일반 페이지 스크립트와 달리 다음 작업을 수행 할 수 있습니다.</span></p> + +<ul> + <li>크로스 도메인의 XHR 요청</li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API">WebExtension APIs</a> 일부 사용</li> + <li>백그라운드 스크립트와<span class="translation"> 메시지를 교환함으로 모든 WebExtension API에 간접적으로 접근</span></li> +</ul> + +<p>컨텐츠 스크립트<span class="translation">는 일반 페이지 스크립트에 직접 접근할 수는 없지만 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">window.postMessage()</a> API를 사용하여 메시지를 교환할 수 있습니다.</span></p> + +<p><span class="translation">일반적으로 </span>컨텐츠 스크립트는<span class="translation"> 자바 스크립트를 지칭하지만, 동일한 매커니즘으로 웹 페이지에 CSS를 삽입할 수 있습니다.</span></p> + +<p>세부내용: <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">content scripts</a> 참조.</p> + +<h2 id="Web_accessible_resources">Web accessible resources</h2> + +<p>Web accessible resources<span class="translation">는</span> 확장앱에 포함되어 있고 컨텐츠 스크립트 및 페이지 스크립트에 엑세스할 수 있게 하려는 이미지, HTML, CSS 및 JavaScript와 같은 리소스입니다. 이 리소스는 특수한 URI를 사용하여 페이지 스크립트 및 컨텐츠 스크립트에서 참조할 수 있습니다.</p> + +<p>예를 들어 컨텐츠 스크립트가 일부 이미지를 웹 페이지에 삽입하려는 경우, 확장앱에 포함시키고 web accessible하게 할 수 있습니다. 그러면 컨텐츠 스크립트에서 src 속성을 통해 이미지를 참조하는 img 태그를 만들고 추가할 수 있습니다.</p> + +<p>자세한 내용은 manifest.json의 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources">web_accessible_resources</a> key의 스펙을 확인하세요.</p> diff --git a/files/ko/mozilla/add-ons/webextensions/api/browsingdata/index.html b/files/ko/mozilla/add-ons/webextensions/api/browsingdata/index.html new file mode 100644 index 0000000000..349b6882f3 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/browsingdata/index.html @@ -0,0 +1,115 @@ +--- +title: browsingData +slug: Mozilla/Add-ons/WebExtensions/API/browsingData +translation_of: Mozilla/Add-ons/WebExtensions/API/browsingData +--- +<div>{{AddonSidebar}}</div> + +<p>WebExtensions 을 통해 사용자가 브라우저를 사용하는 동안 축적된 데이터를 삭제할 수 있는 기능을 제공합니다.</p> + +<p><code>browsingData</code> API는 브라우징 데이터를 다음과 같은 타입으로 구분합니다:</p> + +<ul> + <li>브라우저 캐시</li> + <li>쿠키</li> + <li>다운로드</li> + <li>히스토리</li> + <li>플러그인 데이터</li> + <li>저장된 폼 데이터</li> + <li>저장된 비밀번호saved passwords</li> +</ul> + +<p>You can use the {{WebExtAPIRef("browsingData.remove()")}} function to remove any combination of these types. There are also dedicated functions to remove each particular type of data, such as {{WebExtAPIRef("browsingData.removePasswords()", "removePasswords()")}}, {{WebExtAPIRef("browsingData.removeHistory()", "removeHistory()")}} and so on.</p> + +<p>All the <code>browsingData.remove[X]()</code> functions take a {{WebExtAPIRef("browsingData.RemovalOptions")}} object, which you can use to control two further aspects of data removal:</p> + +<ul> + <li>how far back in time to remove data</li> + <li>whether to remove data only from normal web pages, or also from hosted web apps and add-ons. Note that this option is not yet supported in Firefox.</li> +</ul> + +<p>Finally, this API gives you a {{WebExtAPIRef("browsingData.settings()")}} function that gives you the current value of the settings for the browser's built-in "Clear History" feature.</p> + +<p>To use this API you must have the "browsingData" <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API permission</a>.</p> + +<h2 id="Types">Types</h2> + +<dl> + <dt>{{WebExtAPIRef("browsingData.DataTypeSet")}}</dt> + <dd>Object used to specify the type of data to remove: for example, history, downloads, passwords, and so on.</dd> + <dt>{{WebExtAPIRef("browsingData.RemovalOptions")}}</dt> + <dd>Object used to specify how far back in time to remove data, and whether to remove data added through normal web browsing, by hosted apps, or by add-ons.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{WebExtAPIRef("browsingData.remove()")}}</dt> + <dd>Removes browsing data for the data types specified.</dd> + <dt>{{WebExtAPIRef("browsingData.removeCache()")}}</dt> + <dd>Clears the browser's cache.</dd> + <dt>{{WebExtAPIRef("browsingData.removeCookies()")}}</dt> + <dd>Removes cookies.</dd> + <dt>{{WebExtAPIRef("browsingData.removeDownloads()")}}</dt> + <dd>Removes the list of downloaded files.</dd> + <dt>{{WebExtAPIRef("browsingData.removeFormData()")}}</dt> + <dd>Clears saved form data.</dd> + <dt>{{WebExtAPIRef("browsingData.removeHistory()")}}</dt> + <dd>Clears the browser's history.</dd> + <dt>{{WebExtAPIRef("browsingData.removePasswords()")}}</dt> + <dd>Clears saved passwords.</dd> + <dt>{{WebExtAPIRef("browsingData.removePluginData()")}}</dt> + <dd>Clears data associated with plugins.</dd> + <dt>{{WebExtAPIRef("browsingData.settings()")}}</dt> + <dd>Gets the current value of settings in the browser's "Clear History" feature.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("webextensions.api.browsingData", 2)}}</p> + +<div class="hidden note"> +<p>The "Chrome incompatibilities" section is included from <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities"> https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a> using the <a href="/en-US/docs/Template:WebExtChromeCompat">WebExtChromeCompat</a> macro.</p> + +<p>If you need to update this content, edit <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities">https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a>, then shift-refresh this page to see your changes.</p> +</div> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/browsingData"><code>chrome.browsingData</code></a> API.</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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contentscripts/index.html b/files/ko/mozilla/add-ons/webextensions/api/contentscripts/index.html new file mode 100644 index 0000000000..94061c69dc --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contentscripts/index.html @@ -0,0 +1,38 @@ +--- +title: contentScripts +slug: Mozilla/Add-ons/WebExtensions/API/contentScripts +translation_of: Mozilla/Add-ons/WebExtensions/API/contentScripts +--- +<div>{{AddonSidebar}}</div> + +<p>이 API는 콘텐츠 스크립트를 등록한다. 등록된 콘텐츠 스크립트는 브라우저가 URL 패턴이 일치하는 페이지에 넣는다.</p> + +<p>이 API는 <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts">"content_scripts"</a></code> manifest.json 키와 아주 비슷하다. 단지, <code>"content_scripts"</code>로는 설치할 때 정해진 스크립트와 패턴을 바꿀 수 없지만, <code>contentScripts</code> API로는 스크립트의 등록이나 해제가 실행 중에도 가능하다.</p> + +<p>등록할 스크립트, URL 패턴, 그리고 기타 옵션을 정의하는 객체를 인수로 {{WebExtAPIRef("contentScripts.register()")}}을 호출하면, 반환된 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>는 {{WebExtAPIRef("contentScripts.RegisteredContentScript")}} 객체가 인수인 완료를 수행한다.</p> + +<p><code>RegisteredContentScript</code>는 <code>register()</code>를 호출해 등록할 스크립트를 담는 객체다. 해제는 객체에 정의된 <code>unregister()</code> 메소드로 할 수 있다. 또한, 스크립트를 등록한 페이지를 없애면 스크립트는 자동으로 해제된다. 예를 들어, background 페이지에서 등록했으면 그것들은 background 페이지가 파괴될 때 자동으로 해제된다. 마찬가지로 사이드바나 팝업에서 등록했으면, 사이드바나 팝업이 닫힐 때 자동으로 해제된다.</p> + +<p><code>contentScripts</code> API 자체는 권한 없이 사용할 수 있지만, <code>register()</code>에 전달할 패턴에 대해서는 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">호스트 권한</a>을 가져야 한다.</p> + +<h2 id="자료형">자료형</h2> + +<dl> + <dt>{{WebExtAPIRef("contentScripts.RegisteredContentScript")}}</dt> + <dd> + <p>{{WebExtAPIRef("contentScripts.register()")}} 함수가 반환하는 객체의 자료형으로 등록된 콘텐츠 스크립트를 표현한다. <code>unregister()</code> 메소드로 스스로를 해제할 수 있다.</p> + </dd> +</dl> + +<h2 id="함수">함수</h2> + +<dl> + <dt>{{WebExtAPIRef("contentScripts.register()")}}</dt> + <dd>주어진 콘텐츠 스크립트를 등록한다</dd> +</dl> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("webextensions.api.contentScripts", 10, 1)}}</p> + +<p>{{WebExtExamples("h2")}}</p> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contextmenus/contexttype/index.html b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/contexttype/index.html new file mode 100644 index 0000000000..d6d933b22e --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/contexttype/index.html @@ -0,0 +1,95 @@ +--- +title: menus.ContextType +slug: Mozilla/Add-ons/WebExtensions/API/contextMenus/ContextType +translation_of: Mozilla/Add-ons/WebExtensions/API/menus/ContextType +--- +<div>{{AddonSidebar()}}</div> + +<p>메뉴 항목이 나타나게 하는 콘텍스트들.</p> + +<h2 id="자료형">자료형</h2> + +<p>이 자료형의 값은 문자열이다. 항목은 주어진 콘텍스트일 때 표시된다. 가능한 값은:</p> + +<dl> + <dt>all</dt> + <dd>'all'은 'bookmark', 'tab' 그리고 'tools_menu'를 뺀 나머지 모든 콘텍스트를 다 나열한 것과 같다.</dd> + <dt>audio</dt> + <dd><a href="/en-US/docs/Web/HTML/Element/audio">audio</a> 요소를 콘텍스트-클릭할 때 적용된다. (역주: 콘텍스트-클릭은 보통 마우스 오른쪽 버튼을 클릭하는 것이다)</dd> + <dt>bookmark</dt> + <dd>툴바나 메뉴에서 북마크 항목을 콘텍스트-클릭할 때 적용된다. 현재 북마크 사이드바나 라이브러리 윈도우 항목에서는 동작하지 않는다. manifest에 "bookmarks" <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API 권한</a>이 있어야 한다.</dd> + <dt>browser_action</dt> + <dd>브라우저 액션에서 콘텍스트-클릭을 할 때 적용된다. 최대로 추가할 수 있는 최상위 브라우저 액션 콘텍스트 매뉴 항목의 수는 {{WebExtAPIRef("menus.ACTION_MENU_TOP_LEVEL_LIMIT")}}지만 서버메뉴에는 얼마든지 추가할 수 있다.</dd> + <dt>editable</dt> + <dd>편집 가능한 요소, 가령은 <a href="/en-US/docs/Web/HTML/Element/textarea">textarea</a>를 콘텍스트-클릭할 때 적용된다.</dd> + <dt>frame</dt> + <dd>내포된 <a href="/en-US/docs/Web/HTML/Element/iframe">iframe</a>을 콘텍스트-클릭할 때 적용된다.</dd> + <dt>image</dt> + <dd>이미지를 콘텍스트-클릭할 때 적용된다.</dd> + <dt>link</dt> + <dd>링크를 콘텍스트-클릭할 때 적용된다.</dd> + <dt>page</dt> + <dd>페이지를 콘텍스트-클릭할 때 적용된다. 단, 페이지의 다른 콘텍스트가 적용되지 않을 때만이다(예를 들면, 클릭이 이미지나 내포된 iframe 또는 링크가 아니여야 한다).</dd> + <dt>page_action</dt> + <dd>페이지 액션을 콘텍스트-클릭할 때 적용된다. 최대로 추가할 수 있는 최상위 페이지 액션 콘텍스트 메뉴 항목의 수는 {{WebExtAPIRef("menus.ACTION_MENU_TOP_LEVEL_LIMIT")}}지만 서버메뉴에는 얼마든지 추가할 수 있다.</dd> + <dt>password</dt> + <dd><a href="/en-US/docs/Web/HTML/Element/input/password">password 입력 요소</a>를 콘텍스트-클릭할 때 적용된다.</dd> + <dt>selection</dt> + <dd>페이지 일부가 선택되었을 때 적용된다.</dd> + <dt>tab</dt> + <dd> + <p>탭을 콘텍스트-클릭할 때 적용된다(specifically, this refers to the tab-strip or other user interface element enabling the user to switch from one browser tab to another, not to the page itself).</p> + + <p>파이어폭스 63부터, 탭에서 메뉴 항목을 클릭하면 그것이 설사 현재탭이 아니더라도 클릭한 탭에 대해 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission">activeTab</a> 권한이 승인된다.</p> + </dd> + <dt>tools_menu</dt> + <dd>항목은 브라우저 툴바의 메뉴로 추가된다. 주의해야 할 것은 <code>menus</code> 이름공간을 통해 <code>ContextType</code>에 접근해야지 <code>contextMenus</code> 이름공간으로 하면 안된다.</dd> + <dt>video</dt> + <dd><a href="/en-US/docs/Web/HTML/Element/video">video</a> 요소에 콘텍스트-클릭을 할 때 적용된다.</dd> +</dl> + +<p>"launcher"는 지원되지 않는다.</p> + +<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.menus.ContextType", 10)}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/contextMenus#type-ContextType"><code>chrome.contextMenus</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json"><code>context_menus.json</code></a> in the Chromium code.</p> +</div> + +<div class="hidden"> +<pre>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contextmenus/create/index.html b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/create/index.html new file mode 100644 index 0000000000..9a053e6639 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/create/index.html @@ -0,0 +1,212 @@ +--- +title: menus.create() +slug: Mozilla/Add-ons/WebExtensions/API/contextMenus/create +translation_of: Mozilla/Add-ons/WebExtensions/API/menus/create +--- +<div>{{AddonSidebar()}}</div> + +<p>주어진 객체대로 새 메뉴 항목을 만든다.</p> + +<p>이 함수는 다른 비공기 함수들과 달리 promise가 아니라 새 항목의 ID를 반환한다. 성공과 실패에 대한 처리는 필요하면 콜백으로 한다.</p> + +<p>다른 브라우저와의 호환성을 위해, <code>menus</code> 이름공간 뿐 아니라 <code>contextMenus</code> 이름공간으로도 이 메소드를 사용할 수 있다. 하지만 <code>contextMenus</code>로는 툴 메뉴 항목(<code>contexts: ["tools_menu"]</code>)은 만들 수 없다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">browser.menus.create( + createProperties, // object + function() {...} // optional function +) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>createProperties</code></dt> + <dd><code>object</code>. 새 메뉴 항목의 속성들</dd> + <dd> + <dl class="reference-values"> + <dt><code>checked</code> {{optional_inline}}</dt> + <dd><code>boolean</code>. checkbox나 radio 항목의 초기값: 선택은 <code>true</code>, 선택이 아니면 <code>false</code>. radio 항목이라면 그룹 중에서 하나만 선택된 것으로 할 수 있다.</dd> + <dt><code>command</code> {{optional_inline}}</dt> + <dd> + <p><code>string</code>. 클릭 했을 때 수행할 동작을 기술한다. 가능한 값은:</p> + + <ul> + <li><code>"_execute_browser_action"</code>: 확장의 브라우저 액션을 클릭한 것처럼 한다. 팝업이 있으면 팝업이 열린다.</li> + <li><code>"_execute_page_action"</code>: 확장의 페이지 액션을 클릭한 것처럼 한다. 팝업이 있으면 팝업이 열린다.</li> + <li><code>"_execute_sidebar_action"</code>: 확장의 사이드바를 연다.</li> + </ul> + + <p>항목을 클릭하면 여전히 {{WebExtAPIRef("menus.onClicked")}} 이벤트도 발생한다. 어느게 먼저 인지는 보장되지 않지만 <code>onClicked</code>이 발생하기 전에 명령이 실행될 것이다.</p> + </dd> + <dt><code>contexts</code> {{optional_inline}}</dt> + <dd> + <p><code>{{WebExtAPIRef('menus.ContextType')}}</code>의 <code>배열</code>. 메뉴 항목이 표시할 콘텍스트의 배열. 생략되면:</p> + + <ul> + <li>상위 항목에 콘텍스트가 설정되었으면 그걸 물려받는다.</li> + <li>아니면, 항목은 ["page"]로 설정된다.</li> + </ul> + </dd> + <dt><code>documentUrlPatterns</code> {{optional_inline}}</dt> + <dd><code><code>string</code></code>의 <code>배열</code>. 메뉴 항목의 표시를 URL이 주어진 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match patterns</a>과 일치하는 문서로 제한한다. 프레임에도 적용된다.</dd> + <dt><code>enabled</code> {{optional_inline}}</dt> + <dd><code>boolean</code>. 메뉴 항목이 사용 가능한지 아닌지를 지정한다. 기본값은 <code>true</code>.</dd> + <dt><code>icons</code> {{optional_inline}}</dt> + <dd> + <p><code>object</code>. One or more custom icons to display next to the item. Custom icons can only be set for items appearing in submenus. This property is an object with one property for each supplied icon: the property's name should include the icon's size in pixels, and path is relative to the icon from the extension's root directory. The browser tries to choose a 16x16 pixel icon for a normal display or a 32x32 pixel icon for a high-density display. To avoid any scaling, you can specify icons like this:</p> + + <pre class="brush: json no-line-numbers language-json"><code class="language-json"><span class="key token">"icons":</span> <span class="punctuation token">{</span> + <span class="key token">"16":</span> <span class="string token">"path/to/geo-16.png"</span><span class="punctuation token">,</span> + <span class="key token">"32":</span> <span class="string token">"path/to/geo-32.png"</span> + <span class="punctuation token">}</span></code></pre> + + <p>Alternatively, you can specify a single SVG icon, and it will be scaled appropriately:</p> + + <pre class="brush: json no-line-numbers language-json"><code class="language-json"><span class="key token">"icons":</span> <span class="punctuation token">{</span> + <span class="key token">"16":</span> <span class="string token">"path/to/geo.svg"</span> + <span class="punctuation token">}</span></code></pre> + + <div class="blockIndicator note"> + <p><strong>Note</strong>: The top-level menu item uses the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons">icons</a> specified in the manifest rather than what is specified with this key.</p> + </div> + </dd> + <dt><code>id</code> {{optional_inline}}</dt> + <dd><code>string</code>. The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.</dd> + <dt><code>onclick</code> {{optional_inline}}</dt> + <dd><code>function</code>. A function that will be called when the menu item is clicked. Event pages cannot use this: instead, they should register a listener for {{WebExtAPIRef('menus.onClicked')}}.</dd> + <dt><code>parentId</code> {{optional_inline}}</dt> + <dd><code><code>integer</code></code> or <code><code>string</code></code>. The ID of a parent menu item; this makes the item a child of a previously added item. Note: If you have created more than one menu item, then the items will be placed in a submenu. The submenu's parent will be labeled with the name of the extension.</dd> + <dt><code>targetUrlPatterns</code> {{optional_inline}}</dt> + <dd><code><code>string</code></code>의 <code>배열</code>. <code>documentUrlPatterns</code> 비슷한데, anchor 태그의 <code>href</code> 속성과 img/audio/video 태그의 <code>src</code> 속성에 기초해 걸러지는 것이다. 여기서 URL scheme는 뭐라도 상관없다. 설사 match pattern으로 보통은 허용되지 않는 것이라도 된다.</dd> + <dt><code>title</code> {{optional_inline}}</dt> + <dd> + <p><code>string</code>. The text to be displayed in the item. Mandatory unless <code>type</code> is "separator".</p> + + <p>You can use "%s" in the string. If you do this in a menu item, and some text is selected in the page when the menu is shown, then the selected text will be interpolated into the title. For example, if <code>title</code> is "Translate '%s' to Pig Latin" and the user selects the word "cool", then activates the menu, then the menu item's title will be: "Translate 'cool' to Pig Latin".</p> + + <p>If the title contains an ampersand "&" then the next character will be used as an access key for the item, and the ampersand will not be displayed. Exceptions to this are:</p> + + <ul> + <li>If the next character is also an ampersand: then a single ampersand will be displayed and no access key will be set. In effect, "&&" is used to display a single ampersand.</li> + <li>If the next characters are the interpolation directive "%s": then the ampersand will not be displayed and no access key will be set.</li> + <li>If the ampersand is the last character in the title: then the ampersand will not be displayed and no access key will be set.</li> + </ul> + + <p>Only the first ampersand will be used to set an access key: subsequent ampersands will not be displayed but will not set keys. So "&A and &B" will be shown as "A and B" and set "A" as the access key.</p> + </dd> + <dt><code>type</code> {{optional_inline}}</dt> + <dd>{{WebExtAPIRef('menus.ItemType')}}. The type of menu item: "normal", "checkbox", "radio", "separator". Defaults to "normal".</dd> + <dt><code>visible</code> {{optional_inline}}</dt> + <dd><code>boolean</code>. Whether the item is shown in the menu. Defaults to <code>true</code>.</dd> + </dl> + </dd> + <dt><code>callback</code> {{optional_inline}}</dt> + <dd><code>function</code>. Called when the item has been created. If there were any problems creating the item, details will be available in {{WebExtAPIRef('runtime.lastError')}}.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p><code><code>integer</code></code> or <code><code>string</code></code>. The ID of the newly created item.</p> + +<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.menus.create", 10)}}</p> + +<h2 id="예제">예제</h2> + +<p>이 예제는 페이지에 선택된 텍스트가 있을 때 표시되는 콘텍스트 메뉴 항목을 만든다. 동작은 선택된 텍스트를 콘솔에 로그로 남기는 것이다:</p> + +<pre class="brush: js">browser.menus.create({ + id: "log-selection", + title: "Log '%s' to the console", + contexts: ["selection"] +}); + +browser.menus.onClicked.addListener(function(info, tab) { + if (info.menuItemId == "log-selection") { + console.log(info.selectionText); + } +});</pre> + +<p>이 예제는 두 개의 radio 항목을 추가한다. 선택해서 테두리의 색을 녹색이나 청색으로 할 수 있다. 이 예제는 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission">activeTab 권한</a>이 필요하다.</p> + +<pre class="brush: js">function onCreated() { + if (browser.runtime.lastError) { + console.log("error creating item:" + browser.runtime.lastError); + } else { + console.log("item created successfully"); + } +} + +browser.menus.create({ + id: "radio-green", + type: "radio", + title: "Make it green", + contexts: ["all"], + checked: false +}, onCreated); + +browser.menus.create({ + id: "radio-blue", + type: "radio", + title: "Make it blue", + contexts: ["all"], + checked: false +}, onCreated); + +var makeItBlue = 'document.body.style.border = "5px solid blue"'; +var makeItGreen = 'document.body.style.border = "5px solid green"'; + +browser.menus.onClicked.addListener(function(info, tab) { + if (info.menuItemId == "radio-blue") { + browser.tabs.executeScript(tab.id, { + code: makeItBlue + }); + } else if (info.menuItemId == "radio-green") { + browser.tabs.executeScript(tab.id, { + code: makeItGreen + }); + } +});</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/contextMenus#method-create"><code>chrome.contextMenus</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json"><code>context_menus.json</code></a> in the Chromium code.</p> +</div> + +<div class="hidden"> +<pre>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contextmenus/gettargetelement/index.html b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/gettargetelement/index.html new file mode 100644 index 0000000000..7cb70b5fa7 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/gettargetelement/index.html @@ -0,0 +1,58 @@ +--- +title: menus.getTargetElement() +slug: Mozilla/Add-ons/WebExtensions/API/contextMenus/getTargetElement +translation_of: Mozilla/Add-ons/WebExtensions/API/menus/getTargetElement +--- +<div>{{AddonSidebar}}{{Draft}}</div> + +<p class="summary">주어진 <code>targetElementId</code>에 해당하는 요소를 돌려준다.</p> + +<p>이 함수는 오직 클릭된 요소가 있는 문서에서만 동작한다. so everywhere but in the background page.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">let elem = browser.menus.getTargetElement(targetElementId); +</pre> + +<h3 id="파라메터">파라메터</h3> + +<dl> + <dt><code>targetElementId</code></dt> + <dd><code>{{WebExtAPIRef("menus.onClicked")}}</code> 핸들러 또는 <code>{{WebExtAPIRef("menus.onShown")}}</code> 이벤트에 전달된 <code>{{WebExtAPIRef("menus.OnClickData")}}</code> 객체의 속성</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p><code>targetElementId</code>로 참조되는 요소를 반환한다. <code>targetElementId</code>가 유효하지 않으면 <code>null</code>를 반환한다.</p> + +<h2 id="예제">예제</h2> + +<p>아래 예제는 인수로 전달된 <code>info.targetElementId</code> 값으로 요소를 구하고, 그것을 지운다. 하지만 <code>getTargetElement</code>는 요소가 있는 문서에서만 동작하므로 문서가 있는 탭에 스크립트를 주입하는 형태로 처리하고 있다. </p> + +<pre class="brush: js">browser.menus.create({ + title: "Remove element", + documentUrlPatterns: ["*://*/*"], + contexts: ["audio", "editable", "frame", "image", "link", "page", "password", "video"], + onclick(info, tab) { + browser.tabs.executeScript(tab.id, { + frameId: info.frameId, + code: `browser.menus.getTargetElement(${info.targetElementId}).remove();`, + }); + }, +}); +</pre> + +<p>{{WebExtExamples}}</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("webextensions.api.menus.getTargetElement")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li>{{WebExtAPIRef("menus.create")}}</li> + <li>{{WebExtAPIRef("menus.OnClickData")}}</li> +</ul> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contextmenus/index.html b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/index.html new file mode 100644 index 0000000000..58f5af938b --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/index.html @@ -0,0 +1,183 @@ +--- +title: contextMenus +slug: Mozilla/Add-ons/WebExtensions/API/contextMenus +translation_of: Mozilla/Add-ons/WebExtensions/API/menus +--- +<div>{{AddonSidebar}}</div> + +<p>브라우저의 메뉴 시스템에 항목을 추가한다.</p> + +<p>이 API는 크롬의 <a href="https://developer.chrome.com/extensions/contextMenus">"contextMenus"</a> API를 모델로 했다. 크롬 확장앱이 브라우저의 콘텍스트 메뉴에 항목을 추가하는 API인데, 파이어폭스의 <code>browser.menus</code> API는 여기에 몇 가지 특징을 더했다.</p> + +<p>파이어폭스 55 이전에 이 API의 원래 이름은 <code>contextMenus</code>였고, 지금도 이 이름은 별명으로 유지되므로 다른 브라우저에서도 동작하는 코드를 작성한다면 <code>contextMenus</code>를 사용할 수 있다.</p> + +<p>이 API를 사용하려면 '<code>menus</code>' <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>이 필요하다. <code>menus</code> 대신에 <code>contextMenus</code>를 사용해도 된다. <code>contextMenus</code>를 사용했으면 API도 <code>browser.contextMenus</code>를 써야 한다.</p> + +<p>콘텐트 스크립트에서는 <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/getTargetElement">menus.getTargetElement()</a></code>만 사용할 수 있다.</p> + +<h2 id="메뉴_항목_만들기">메뉴 항목 만들기</h2> + +<p>메뉴 항목을 만들려면 {{WebExtAPIRef("contextMenus.create()")}} 메소드를 호출한다. 인수로 항목의 ID, 종류, 어떤 콘텍스트일 때 표시되는지 등이 포함된 객체를 전달한다.</p> + +<p>항목의 클릭을 처리하려면 {{WebExtAPIRef("contextMenus.onClicked")}} 이벤트에 리스너를 추가한다. 리스너는 상세한 이벤트 정보를 담고 있는{{WebExtAPIRef("contextMenus.OnClickData")}} 객체를 받는다.</p> + +<p>콘텍스트 메뉴는 네 종류다. <code>create()</code>에 주어지는 <code>type</code> 속성으로 지정한다:</p> + +<ul> + <li>"normal": 그냥 라벨만 표시된다.</li> + <li>"checkbox": 라벨 옆에 추가로 체크표시가 있어 두가지 상태를 표현하는 메뉴 항목이다. 클릭할 때마다 라벨표시가 토글된다. 리스너는 두가지 속성을 추가로 받게 된다: "checked"는 현재 체크 상태를 가리키고, "wasChecked"는 클릭 이벤트 전의 체크 상태를 가리킨다.</li> + <li>"radio": 여러 선택지 중의 하나라는 것을 표현하는 메뉴 항목이다. 라벨 옆에 체크표시가 있고, "checked"와 "wasChecked" 속성이 있다는 것은 checkbox와 같다. 다른 점은 radio 항목을 하나 이상 만들어 그룹이 되면, 오직 클릭하는 하나만 선택이 된다는 것이다.</li> + <li>"separator": 항목을 그룹짓는 구분선이다.</li> +</ul> + +<p>메뉴 항목을 하나 이상 만들면 그 항목들은 서버메뉴로 표시되고, 상위메뉴의 라벨은 확장의 이름이 된다. 예를 들어, "Menu demo"라는 확장이 있고, 그것이 두 개의 콘텍스트 메뉴 항목을 추가했다면:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15431/menus-1.png" style="display: block; height: 406px; margin-left: auto; margin-right: auto; width: 500px;"></p> + +<h2 id="아이콘">아이콘</h2> + +<p><a href="/en-US/Add-ons/WebExtensions/manifest.json/icons">"icons" manifest 키</a>로 확장이 아이콘을 가졌으면, 콘텍스트 메뉴 항목은 라벨 옆에 아이콘을 함께 표시한다. 보통의 경우 16x16 픽셀이 표시되고, 고해상도이면 32x32 픽셀의 아이콘이 표시된다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15433/menus-2.png" style="display: block; height: 409px; margin-left: auto; margin-right: auto; width: 500px;"></p> + +<p>서버메뉴에 대해서만 {{WebExtAPIRef("menus.create()")}}에 <code>icons</code> 옵션을 전달해서 아이콘을 지정할 수 있다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15435/menus-3.png" style="display: block; height: 396px; margin-left: auto; margin-right: auto; width: 500px;"></p> + +<h2 id="예제">예제</h2> + +<p>아래 콘텍스트 메뉴에는 4개 항목이 있다: 보통 항목 하나, 위-아래가 구분선인 두 개의 라디오 항목, 그리고 체크박스 항목 하나다. 라디오 항목에는 따로 아이콘이 지정되었다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15437/menus-4.png" style="display: block; height: 790px; margin-left: auto; margin-right: auto; width: 500px;">이 서버메뉴는 아래 코드로 만들 수 있다:</p> + +<pre class="brush: js">browser.menus.create({ + id: "remove-me", + title: browser.i18n.getMessage("menuItemRemoveMe"), + contexts: ["all"] +}, onCreated); + +browser.menus.create({ + id: "separator-1", + type: "separator", + contexts: ["all"] +}, onCreated); + +browser.menus.create({ + id: "greenify", + type: "radio", + title: browser.i18n.getMessage("menuItemGreenify"), + contexts: ["all"], + checked: true, + icons: { + "16": "icons/paint-green-16.png", + "32": "icons/paint-green-32.png" + } +}, onCreated); + +browser.menus.create({ + id: "bluify", + type: "radio", + title: browser.i18n.getMessage("menuItemBluify"), + contexts: ["all"], + checked: false, + icons: { + "16": "icons/paint-blue-16.png", + "32": "icons/paint-blue-32.png" + } +}, onCreated); + +browser.menus.create({ + id: "separator-2", + type: "separator", + contexts: ["all"] +}, onCreated); + +var checkedState = true; + +browser.menus.create({ + id: "check-uncheck", + type: "checkbox", + title: browser.i18n.getMessage("menuItemUncheckMe"), + contexts: ["all"], + checked: checkedState +}, onCreated);</pre> + +<h2 id="타입">타입</h2> + +<dl> + <dt>{{WebExtAPIRef("contextMenus.ContextType")}}</dt> + <dd>메뉴가 표시되게 하는 여러 콘텍스트. 가능한 값은: "all", "audio", "browser_action", "editable", "frame", "image", "link", "page", "page_action", "password", "selection", "tab", "video".</dd> + <dt>{{WebExtAPIRef("contextMenus.ItemType")}}</dt> + <dd>메뉴 항목의 종류: "normal", "checkbox", "radio", "separator".</dd> + <dt>{{WebExtAPIRef("contextMenus.OnClickData")}}</dt> + <dd>메뉴 항목이 클릭됐을 때 보내지는 정보.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<dl> + <dt>{{WebExtAPIRef("contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT")}}</dt> + <dd>최상위에 추가할 수 있는 ContextType이 "browser_action"이나 "page_action"인 메뉴 항목의 최대 수량.</dd> +</dl> + +<h2 id="함수">함수</h2> + +<dl> + <dt>{{WebExtAPIRef("contextMenus.create()")}}</dt> + <dd>새 콘텍스트 메뉴 항목을 만든다.</dd> + <dt>{{WebExtAPIRef("contextMenus.update()")}}</dt> + <dd>전에 만든 콘텍스트 메뉴 항목을 갱신한다.</dd> + <dt>{{WebExtAPIRef("contextMenus.remove()")}}</dt> + <dd>콘텍스트 메뉴 항목을 지운다.</dd> + <dt>{{WebExtAPIRef("contextMenus.removeAll()")}}</dt> + <dd>확자앱에 추가된 모든 콘텍스트 메뉴 항목을 지운다.</dd> +</dl> + +<h2 id="이벤트">이벤트</h2> + +<dl> + <dt>{{WebExtAPIRef("contextMenus.onClicked")}}</dt> + <dd>콘텍스트 메뉴 항목이 클릭하면 발생한다.</dd> +</dl> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{ Compat("webextensions.api.menus", 1, "true") }}</p> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/contextMenus"><code>chrome.contextMenus</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/context_menus.json"><code>context_menus.json</code></a> in the Chromium code.</p> +</div> + +<div class="hidden"> +<pre>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/contextmenus/onshown/index.html b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/onshown/index.html new file mode 100644 index 0000000000..1fd716e3bb --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/contextmenus/onshown/index.html @@ -0,0 +1,144 @@ +--- +title: menus.onShown +slug: Mozilla/Add-ons/WebExtensions/API/contextMenus/onShown +translation_of: Mozilla/Add-ons/WebExtensions/API/menus/onShown +--- +<div>{{AddonSidebar()}}</div> + +<p>Fired when the browser has shown a menu.</p> + +<p>An extension can use this event to update its menu items using information that's only available once the menu is shown. Typically an extension will figure out the update in its <code>onShown</code> handler and then call {{WebExtAPIRef("menus.refresh()")}} to update the menu itself.</p> + +<p>The handler can add, remove, or update menu items.</p> + +<p>For example, the <a href="https://github.com/mdn/webextensions-examples/tree/master/menu-labelled-open">menu-labelled-open</a> example extension adds a menu item that's shown when the user clicks a link, and that, when clicked, just opens the link. It uses <code>onShown</code> and <code>refresh()</code> to annotate the menu item with the hostname for the link, so the user can easily see where they will go before they click.</p> + +<p>Note that an extension should not take too much time before calling <code>refresh()</code>, or the update will be noticeable to the user.</p> + +<p>The handler is passed some information about the menu and its contents, and some information from the page (such as the link and/or selection text). To get access to the information from the page, your extension must have the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission</a> for it.</p> + +<p>If the <code>onShown</code> handler calls any asynchronous APIs, then it's possible that the menu has been closed again before the handler resumes execution. Because of this, if a handler calls any asynchronous APIs, it should check that the menu is still being displayed before it updates the menu. For example:</p> + +<pre class="brush: js">var lastMenuInstanceId = 0; +var nextMenuInstanceId = 1; + +browser.menus.onShown.addListener(async function(info, tab) { + var menuInstanceId = nextMenuInstanceId++; + lastMenuInstanceId = menuInstanceId; + + // Call an async function + await .... ; + + // After completing the async operation, check whether the menu is still shown. + if (menuInstanceId !== lastMenuInstanceId) { + return; // Menu was closed and shown again. + } + // Now use menus.create/update + menus.refresh. +}); + +browser.menus.onHidden.addListener(function() { + lastMenuInstanceId = 0; +});</pre> + +<p>Note that it is possible to call menus API functions synchronously, and in this case you don't have to perform this check:</p> + +<pre class="brush: js">browser.menus.onShown.addListener(async function(info, tab) { + browser.menus.update(menuId, ...); + // Note: Not waiting for returned promise. + browser.menus.refresh(); +});</pre> + +<p>However, if you call these APIs asynchronously, then you do have to perform the check:</p> + +<pre class="brush: js">browser.menus.onShown.addListener(async function(info, tab) { + var menuInstanceId = nextMenuInstanceId++; + lastMenuInstanceId = menuInstanceId; + + await browser.menus.update(menuId, ...); + // must now perform the check + if (menuInstanceId !== lastMenuInstanceId) { + return; + } + browser.menus.refresh(); +});</pre> + +<p>Firefox makes this event available via the <code>contextMenus</code> namespace as well as the <code>menus</code> namespace.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">browser.menus.onShown.addListener(listener) +browser.menus.onShown.removeListener(listener) +browser.menus.onShown.hasListener(listener) +</pre> + +<p>Events have three functions:</p> + +<dl> + <dt><code>addListener(listener)</code></dt> + <dd>Adds a listener to this event.</dd> + <dt><code>removeListener(listener)</code></dt> + <dd>Stop listening to this event. The <code>listener</code> argument is the listener to remove.</dd> + <dt><code>hasListener(listener)</code></dt> + <dd>Check whether <code>listener</code> is registered for this event. Returns <code>true</code> if it is listening, <code>false</code> otherwise.</dd> +</dl> + +<h2 id="addListener_syntax">addListener syntax</h2> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>callback</code></dt> + <dd> + <p>Function that will be called when this event occurs. The function will be passed the following arguments:</p> + + <dl class="reference-values"> + <dt><code>info</code></dt> + <dd> + <p><code>Object</code>. This is just like the {{WebExtAPIRef('menus.OnClickData')}} object, except it contains two extra properties:</p> + + <ul> + <li><code>contexts</code>: an array of all the {{WebExtAPIRef("menus.ContextType", "contexts")}} that are applicable to this menu.</li> + <li><code>menuIds</code>: an array of IDs of all menu items belonging to this extension that are being shown in this menu.</li> + </ul> + + <p>Compared with <code>menus.OnClickData</code>, the <code>info</code> object also omits the <code>menuItemId</code> and <code>modifiers</code> properties, because of course these are not available until a menu item has been selected.</p> + + <p>The <code>contexts</code>, <code>menuIds</code>, <code>frameId</code>, and <code>editable</code> properties are always provided. All the other properties in <code>info</code> are only provided if the extension has the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission</a> for the page.</p> + </dd> + </dl> + + <dl class="reference-values"> + <dt><code>tab</code></dt> + <dd>{{WebExtAPIRef('tabs.Tab')}}. The details of the tab where the click took place. If the click did not take place in or on a tab, this parameter will be missing.</dd> + </dl> + </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.menus.onShown", 10)}}</p> + +<h2 id="예제">예제</h2> + +<p>This example listens for the context menu to be shown over a link, then updates the <code>openLabelledId</code> menu item with the link's hostname:</p> + +<pre class="brush: js">function updateMenuItem(linkHostname) { + browser.menus.update(openLabelledId, { + title: `Open (${linkHostname})` + }); + browser.menus.refresh(); +} + +browser.menus.onShown.addListener(info => { + if (!info.linkUrl) { + return; + } + let linkElement = document.createElement("a"); + linkElement.href = info.linkUrl; + updateMenuItem(linkElement.hostname); +}); +</pre> + +<p>{{WebExtExamples}}</p> diff --git a/files/ko/mozilla/add-ons/webextensions/api/index.html b/files/ko/mozilla/add-ons/webextensions/api/index.html new file mode 100644 index 0000000000..a55642e38a --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/index.html @@ -0,0 +1,51 @@ +--- +title: JavaScript APIs +slug: Mozilla/Add-ons/WebExtensions/API +tags: + - NeedsTranslation + - TopicStub + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API +--- +<div>{{AddonSidebar}}</div> + +<div> +<p>The WebExtension JavaScript APIs can be used inside the add-on's <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_scripts">background scripts</a> and in any other documents bundled with the add-on, including <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_action">browser action</a> or <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Page_actions">page action</a> popups, <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Sidebars">sidebars</a>, <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Options_pages">options pages</a>, or <a href="/en-US/Add-ons/WebExtensions/manifest.json/chrome_url_overrides">new tab pages</a>. A few of these APIs can also be accessed by an add-on's <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Content_scripts">content scripts</a> (see the <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs">list in the content script guide</a>).</p> + +<p>To use the more powerful APIs you need to <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions">request permission</a> in your add-on's manifest.json.</p> + +<p>You can access the APIs using the <code>browser</code> namespace:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">logTabs</span><span class="punctuation token">(</span>tabs<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>tabs<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +browser<span class="punctuation token">.</span>tabs<span class="punctuation token">.</span><span class="function token">query</span><span class="punctuation token">(</span><span class="punctuation token">{</span>currentWindow<span class="punctuation token">:</span> <span class="keyword token">true</span><span class="punctuation token">}</span><span class="punctuation token">,</span> logTabs<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> +</div> + +<div> +<p>Many of the APIs are asynchronous, returning a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">function</span> <span class="function token">logCookie</span><span class="punctuation token">(</span>c<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span>c<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +<span class="keyword token">function</span> <span class="function token">logError</span><span class="punctuation token">(</span>e<span class="punctuation token">)</span> <span class="punctuation token">{</span> + console<span class="punctuation token">.</span><span class="function token">error</span><span class="punctuation token">(</span>e<span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span> + +<span class="keyword token">var</span> setCookie <span class="operator token">=</span> browser<span class="punctuation token">.</span>cookies<span class="punctuation token">.</span><span class="keyword token">set</span><span class="punctuation token">(</span> + <span class="punctuation token">{</span>url<span class="punctuation token">:</span> <span class="string token">"https://developer.mozilla.org/"</span><span class="punctuation token">}</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span> +setCookie<span class="punctuation token">.</span><span class="function token">then</span><span class="punctuation token">(</span>logCookie<span class="punctuation token">,</span> logError<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> +</div> + +<div> +<p>Note that this is different from Google Chrome's extension system, which uses the <code>chrome</code> namespace instead of <code>browser</code>, and which uses callbacks instead of promises for asynchronous functions. As a porting aid, the Firefox implementation of WebExtensions supports <code>chrome</code> and callbacks as well as <code>browser</code> and promises. Mozilla has also written a polyfill which enables code that uses <code>browser</code> and promises to work unchanged in Chrome: <a class="external external-icon" href="https://github.com/mozilla/webextension-polyfill">https://github.com/mozilla/webextension-polyfill</a>.</p> + +<p>Microsoft Edge uses the <code>browser</code> namespace, but doesn't yet support promise-based asynchronous APIs. In Edge, for the time being, asynchronous APIs must use callbacks.</p> + +<p>Not all browsers support all the APIs: for the details, see <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs">Browser support for JavaScript APIs</a>.</p> +</div> + +<div>{{SubpagesWithSummaries}}</div> diff --git a/files/ko/mozilla/add-ons/webextensions/api/pageaction/index.html b/files/ko/mozilla/add-ons/webextensions/api/pageaction/index.html new file mode 100644 index 0000000000..7d5ad34823 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/pageaction/index.html @@ -0,0 +1,99 @@ +--- +title: pageAction +slug: Mozilla/Add-ons/WebExtensions/API/pageAction +translation_of: Mozilla/Add-ons/WebExtensions/API/pageAction +--- +<div>{{AddonSidebar}}</div> + +<p><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Page_actions">페이지 액션</a>은 브라우저의 주소창에 있는 아이콘이다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12960/page-action.png" style="display: block; height: 262px; margin-left: auto; margin-right: auto; width: 850px;"></p> + +<p>아이콘 클릭에 대한 대응은 리스너를 등록하고 클릭 이벤트를 기다리는 것이나, <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Popups">팝업창</a>이 열리게 하는 것일 수 있다.</p> + +<p>팝업창은 보통의 웹페이지처럼 HTML, CSS, 그리고 자바스크립트로 내용과 동작을 작성할 수 있다. 팝업창에서 실행되는 자바스크립트는 백그라운드 스크립트와 마찬가지로 모든 확장앱 API를 사용할 수 있다.</p> + +<p><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a>의 <a href="/en-US/Add-ons/WebExtensions/manifest.json/page_action">page_action 키</a>에 페이지 액션의 대부분의 속성들을 정의할 수 있지만, 이것들은 확정되는 것이라 이후에 바꿀 수 없다. 하지만 이 API는 그것들을 프로그램적으로 재정의하는 것도 가능하다. 그러나 API는 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a>에 <a href="/en-US/Add-ons/WebExtensions/manifest.json/page_action">page_action</a> 키가 있어야만 사용할 수 있게 되므로 설사 모든 것을 프로그램적으로 할 계획이더라도 <a href="/en-US/Add-ons/WebExtensions/manifest.json/page_action">page_action 키</a>는 있어야 한다.</p> + +<p>페이지 액션은 특정 페이지에만 적절한 동작들을 위한 것이다(이럴테면 "현재 탭을 북마크하기" 같은). 그렇지 않고, 브라우저가 전반적으로 관련되는 동작이라면(가령은 "모든 북마크 보기" 라면) 브라우저 액션을 대신 사용하라.</p> + +<h2 id="자료형">자료형</h2> + +<dl> + <dt>{{WebExtAPIRef("pageAction.ImageDataType")}}</dt> + <dd>이미지에 대한 픽셀 자료.</dd> +</dl> + +<h2 id="함수">함수</h2> + +<dl> + <dt>{{WebExtAPIRef("pageAction.show()")}}</dt> + <dd>지정한 탭에 페이지 액션을 보인다.</dd> + <dt>{{WebExtAPIRef("pageAction.hide()")}}</dt> + <dd>지정한 탭의 페이지 액션을 숨긴다.</dd> + <dt>{{WebExtAPIRef("pageAction.isShown()")}}</dt> + <dd>페이지 액션이 보이는지 아닌지 검사한다.</dd> + <dt>{{WebExtAPIRef("pageAction.setTitle()")}}</dt> + <dd>페이지 액션의 제목을 설정한다. 이것은 페이지 액션위에 툴팁으로 표시된다.</dd> + <dt>{{WebExtAPIRef("pageAction.getTitle()")}}</dt> + <dd>페이지 액션의 제목을 얻는다.</dd> + <dt>{{WebExtAPIRef("pageAction.setIcon()")}}</dt> + <dd>페이지 액션의 아이콘을 설정한다.</dd> + <dt>{{WebExtAPIRef("pageAction.setPopup()")}}</dt> + <dd>페이지 액션의 팝업 URL을 설정한다.</dd> + <dt>{{WebExtAPIRef("pageAction.getPopup()")}}</dt> + <dd>페이지 액션의 팝업 URL을 얻는다.</dd> + <dt>{{WebExtAPIRef("pageAction.openPopup()")}}</dt> + <dd>페이지 액션의 팝업을 연다.</dd> +</dl> + +<h2 id="이벤트">이벤트</h2> + +<dl> + <dt>{{WebExtAPIRef("pageAction.onClicked")}}</dt> + <dd>페이지 액션의 아이콘이 클릭되면 발생한다. 페이지 액션이 팝업이 설정되어 있으면 발생하지 않는다.</dd> +</dl> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("webextensions.api.pageAction")}}</p> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/pageAction"><code>chrome.pageAction</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/page_action.json"><code>page_action.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/pageaction/show/index.html b/files/ko/mozilla/add-ons/webextensions/api/pageaction/show/index.html new file mode 100644 index 0000000000..523887dd72 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/pageaction/show/index.html @@ -0,0 +1,93 @@ +--- +title: pageAction.show() +slug: Mozilla/Add-ons/WebExtensions/API/pageAction/show +translation_of: Mozilla/Add-ons/WebExtensions/API/pageAction/show +--- +<div>{{AddonSidebar()}}</div> + +<p>지정한 탭의 페이지 액션을 보인다. 페이지 액션은 해당 탭이 활성일 때 표시된다.</p> + +<p><code>show()</code>는 설정된 URL 패턴과 상관없이 동작한다. 따라서 <a href="https://developer.mozilla.org/Add-ons/WebExtensions/manifest.json/page_action"><code>show_matches</code></a>와 일치하지 않아도 <a href="https://developer.mozilla.org/Add-ons/WebExtensions/manifest.json/page_action"><code>hide_matches</code></a>여도 표시된다.</p> + +<p><code>show()</code>는 아무런 내용도 없는 탭에는 효과가 없다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">browser.pageAction.show( + tabId // integer +) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>tabId</code></dt> + <dd><code>integer</code>. 페이지 액션을 표시할 탭의 ID</dd> + <dt> + <h3 id="반환값">반환값</h3> + + <p>값 없이 해결을 수행하는 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>.</p> + </dt> +</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.pageAction.show")}}</p> + +<h2 id="예제">예제</h2> + +<p>콘텍스트 메뉴가 선택되면 페이지 액션을 보이는 예제다. 메뉴를 만들려면 <code>contextMenus</code> <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>이 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest</a>에 필요하다.</p> + +<pre class="brush: js">browser.contextMenus.create({ + id: "show", + title: "Show page action" +}); + +browser.contextMenus.onClicked.addListener(function(info, tab) { + if (info.menuItemId == "show") { + browser.pageAction.show(tab.id); + } +}); +</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/pageAction#method-show"><code>chrome.pageAction</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/page_action.json"><code>page_action.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/index.html new file mode 100644 index 0000000000..254cd7bdcf --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/index.html @@ -0,0 +1,111 @@ +--- +title: storage +slug: Mozilla/Add-ons/WebExtensions/API/storage +tags: + - 비표준 + - 웹확장 + - 인터페이스 + - 저장소 + - 참조 + - 확장 +translation_of: Mozilla/Add-ons/WebExtensions/API/storage +--- +<div>{{AddonSidebar}}</div> + +<p>웹확장이 데이터를 저장하고, 확인하고, 저장된 항목의 변화를 감시할 수 있도록 해 준다.</p> + +<p>저장소 시스템은 <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage API</a>에 기반하는데 약간의 차이가 있다:</p> + +<ul> + <li>비동기로 동작한다.</li> + <li>값은 도메인이 아니라 확장에 딸린 것이다 (예. 같은 키/값 쌍일 경우 확장의 모든 스크립트에서 사용할 수 있다).</li> + <li>저장된 값은 그저 문자열이 아니라 JSON-화가능 값이다. 배열과 객체도 된다. 단 포함된 값도 JSON으로 나타낼 수 있어야 하므로 DOM의 노드는 안된다. 값을 저장하기 전에 JSON 문자열로 바꿀 필요는 없지만, 내부적으로 JSON으로 다뤄지므로 JSON화가능임은 요구된다.</li> + <li>같은 API 호출로 다수의 키/값 쌍을 다룰 수 있다.</li> +</ul> + +<p>이 API를 사용하려면 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json</a> 파일에 "storage" <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>이 포함돼야 한다.</p> + +<p>각 웹확장은 자신만의 저장소를 따로 가진다. which can be split into different types of storage.</p> + +<p>이 API는 {{domxref("Window.localStorage")}}와 비슷하지만, 확장 코드가 확장 관련 데이터를 저장하는데 <code>Window.localStorage</code>를 사용하지 말 것을 권장한다. 사적이 이유로 사용자가 방문 기록이나 데이터를 지우는 다양한 상황에서 확장이 localStorage API로 저장된 데이터는 지워지지만, <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local">storage.local</a></code> API로 저장한 데이터는 정확하게 유지된다.</p> + +<h2 id="자료형">자료형</h2> + +<dl> + <dt>{{WebExtAPIRef("storage.StorageArea")}}</dt> + <dd>저장소 영역을 표현하는 객체.</dd> + <dt>{{WebExtAPIRef("storage.StorageChange")}}</dt> + <dd>저장소 영역의 변화를 표현하는 객체.</dd> +</dl> + +<h2 id="속성">속성</h2> + +<p><code>storage</code>에는 저장소 영역의 가능한 형식을 나타내는 세가지 속성이 있다.</p> + +<dl> + <dt>{{WebExtAPIRef("storage.sync")}}</dt> + <dd><code>sync</code> 저장소 영역을 표현한다. <code>sync</code> 저장소의 항목은 브라우저에 동기되므로 사용자가 로그인한 모든 브라우저에서 사용할 수 있다. 기기가 달라도 된다.</dd> + <dt>{{WebExtAPIRef("storage.local")}}</dt> + <dd><code>local</code> 저장소 영역을 표현한다. <code>local</code> 저장소의 항목은 확장이 설치된 기기에 한정된다.</dd> + <dt>{{WebExtAPIRef("storage.managed")}}</dt> + <dd><code>managed</code> 저장소 영역을 표현한다. <code>managed</code> 저장소의 항목은 도메인 관리자가 설정하고 확장은 읽을 수만 있으므로 변경을 시도하면 에러가 발생한다.</dd> +</dl> + +<h2 id="이벤트">이벤트</h2> + +<dl> + <dt>{{WebExtAPIRef("storage.onChanged")}}</dt> + <dd>저장소 영역의 항목에 변화가 있으면 발생한다.</dd> +</dl> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("webextensions.api.storage")}}</p> + +<div class="hidden note"> +<p>The "Chrome incompatibilities" section is included from <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities"> https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a> using the <a href="/en-US/docs/Template:WebExtChromeCompat">WebExtChromeCompat</a> macro.</p> + +<p>If you need to update this content, edit <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities">https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a>, then shift-refresh this page to see your changes.</p> +</div> + +<h3 id="Edge_incompatibilities">Edge incompatibilities</h3> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/storage"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/local/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/local/index.html new file mode 100644 index 0000000000..2d8e31c579 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/local/index.html @@ -0,0 +1,88 @@ +--- +title: storage.local +slug: Mozilla/Add-ons/WebExtensions/API/storage/local +tags: + - 로칼 + - 비표준 + - 저장소 +translation_of: Mozilla/Add-ons/WebExtensions/API/storage/local +--- +<div>{{AddonSidebar()}}</div> + +<p><code>local</code> 저장소 영역을 표현한다. <code>local</code> 저장소의 항목은 확장이 설치된 기기에 제한된다.</p> + +<p>브라우저는 local 저장소에 저장할 수 있는 데이터의 양을 제한한다:</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Unlimited_storage">"unlimitedStorage" 권한</a>이 없으면 크롬은 데이터의 양을 5M로 제한한다.</li> + <li>파이어폭스는 버전 56부터 "unlimitedStorage" 권한을 요청할 수 있다. 아직은 저장 용량을 제한하지는 않지만, 앞으로 그렇게 할 것이므로 큰 용량의 저장할 의도라면 지금 "unlimitedStorage" 권한을 요청하는 것이 좋다.</li> +</ul> + +<p>확장이 제거되면, 그것과 연결된 local 저장소는 지워진다.</p> + +<p>파이어폭스에서는 확장을 제거해도 local 저장소를 브라우저가 지우지 않도록 막을 수 있다. "about:config"에서 "keepUuidOnUninstall"와 "keepStorageOnUninstall" 두 브라우저 기본 설정을 <code>true</code>로 고치면 된다. 이 특징은 개발자가 확장을 테스트하는데 도움을 주려는 것이다. 확장 스스로 이 값들을 바꿀 수는 없다.</p> + +<p>이 API는 {{domxref("Window.localStorage")}}와 비슷하지만, 확장 코드가 확장 관련 데이터를 저장하는데 <code>Window.localStorage</code>를 사용하지 말 것을 권장한다. 사적이 이유로 사용자가 방문 기록이나 데이터를 지우는 다양한 상황에서 확장이 localStorage API로 저장된 데이터는 지워지지만, <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/local">storage.local</a></code> API로 저장한 데이터는 정확하게 유지된다.</p> + +<h2 id="메소드">메소드</h2> + +<p><code>local</code> 객체는 {{WebExtAPIRef("storage.StorageArea")}} 자료형에 정의된 메소드로 구현되었다:</p> + +<dl> + <dt>{{WebExtAPIRef("storage.StorageArea.get()")}}</dt> + <dd>저장소 영역에서 하나 이상의 항목을 가져온다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.getBytesInUse()")}}</dt> + <dd>저장소의 사용된 크기를 바이트단위로 얻는다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.set()")}}</dt> + <dd>저장소에 하나 이상의 항목을 설정한다. 이미 있는 항목은 교체된다. 값을 설정하면 {{WebExtAPIRef("storage.onChanged")}} 이벤트가 발생한다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.remove()")}}</dt> + <dd>저장소에서 하나 이상의 값을 지운다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.clear()")}}</dt> + <dd>저장소의 모든 항목을 지워서 비운다.</dd> +</dl> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("webextensions.api.storage.local")}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/storage#property-local"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/get/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/get/index.html new file mode 100644 index 0000000000..182a655ad6 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/get/index.html @@ -0,0 +1,125 @@ +--- +title: StorageArea.get() +slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/get +translation_of: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/get +--- +<div>{{AddonSidebar()}}</div> + +<p>저장소에서 하나 이상의 항목을 가져온다.</p> + +<p>비동기 함수로 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>를 돌려준다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox">let gettingItem = browser.storage.<storageType>.get( + keys // null, string, object or array of strings +) +</pre> + +<p><code><storageType></code>는 읽기 가능한 저장소 중의 하나다 — {{WebExtAPIRef("storage.sync", "sync")}}, {{WebExtAPIRef("storage.local", "local")}}, 또는 {{WebExtAPIRef("storage.managed", "managed")}}.</p> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>keys</code></dt> + <dd>저장소에서 가져올 항목을 지정하는 키 (문자열) 또는 키들 (문자열의 배열 또는 기본값이 주어진 객체). 빈 문자열, 객체, 또는 배열이 주어지면 빈 객체가 반환된다. null이나 undefined가 주어지면 전체 항목이 반환된다.</dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>반환된 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>는 저장소에서 찾은 모든 항목을 담은 객체를 인수로 완료를 수행한다. 실패하면 에러 문장으로 거부가 수행된다. managed 저장소가 설정되어 있지 않으면 <code>undefined</code>가 반환된다.</p> + +<div class="warning"> +<p>When used within a content script in Firefox versions prior to 52, the Promise returned by <code>browser.storage.local.get()</code> is fulfilled with an Array containing one Object. The Object in the Array contains the <code>keys</code> found in the storage area, as described above. The Promise is correctly fulfilled with an Object when used in the background context (background scripts, popups, options pages, etc.). When this API is used as <code>chrome.storage.local.get()</code>, it correctly passes an Object to the callback function.</p> +</div> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("webextensions.api.storage.StorageArea.get")}}</p> + +<h2 id="예제">예제</h2> + +<p>두 항목을 담고 있는 저장소를 가정한다:</p> + +<pre class="brush: js">// storage contains two items, +// "kitten" and "monster" +browser.storage.local.set({ + kitten: {name:"Mog", eats:"mice"}, + monster: {name:"Kraken", eats:"people"} +});</pre> + +<p>promise에 대한 성공과 실패 핸들러를 정의한다:</p> + +<pre class="brush: js">function onGot(item) { + console.log(item); +} + +function onError(error) { + console.log(`Error: ${error}`); +}</pre> + +<p><code>keys</code> 인수없이 전체를 구한다:</p> + +<pre class="brush: js">let gettingItem = browser.storage.local.get(); +gettingItem.then(onGot, onError); + +// -> Object { kitten: Object, monster: Object }</pre> + +<p>빈 인수는 빈 객체를 반환한다:</p> + +<pre class="brush: js">// with an empty array, retrieve nothing +let gettingItem = browser.storage.local.get([]); +gettingItem.then(onGot, onError); + +// -> Object { }</pre> + +<p>이름을 인수로 하면 일치하는 항목을 담은 객체를 반환한다:</p> + +<pre class="brush: js">let gettingItem = browser.storage.local.get("kitten"); +gettingItem.then(onGot, onError); + +// -> Object { kitten: Object }</pre> + +<p>이름들을 인수로 하면 전체 일치 항목을 모두 담은 객체를 반환한다:</p> + +<pre class="brush: js">let gettingItem = browser.storage.local.get(["kitten", "monster", "grapefruit"]); +gettingItem.then(onGot, onError); + +// -> Object { kitten: Object, monster: Object } </pre> + +<p>객체를 인수로 하면 주어진 객체의 키들을 이름으로 항목을 찾아서 돌려준다:</p> + +<pre class="brush: js">let gettingItem = browser.storage.local.get({ + kitten: "no kitten", + monster: "no monster", + grapefruit: { + name: "Grape Fruit", + eats: "Water" + } +}); + +// -> Object { kitten: Object, monster: Object, grapefruit: Object } +</pre> + +<p>{{WebExtExamples}}</p> + +<h3 id="크롬_예제">크롬 예제</h3> + +<p>크롬에서는 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>가 아니라 콜백 형태로 해야 한다.</p> + +<pre class="brush: js">chrome.storage.local.get("kitten", function(items){ + console.log(items.kitten); // -> {name:"Mog", eats:"mice"} +});</pre> + +<p class="brush: js">또는 화살표 함수로 할 수 있다.</p> + +<pre class="brush: js">chrome.storage.local.get("kitten", items=>{ + console.log(items.kitten); // -> {name:"Mog", eats:"mice"} +});</pre> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/storage"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/index.html new file mode 100644 index 0000000000..00d46ba6ec --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/index.html @@ -0,0 +1,85 @@ +--- +title: storage.StorageArea +slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea +tags: + - API + - Add-ons + - Extensions + - NeedsTranslation + - Non-standard + - Reference + - Storage + - StorageArea + - TopicStub + - Type + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea +--- +<div>{{AddonSidebar()}}</div> + +<p>StorageArea is an object representing a storage area.</p> + +<h2 id="Type">Type</h2> + +<p>Values of this type are objects.</p> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{WebExtAPIRef("storage.StorageArea.get()")}}</dt> + <dd>Retrieves one or more items from the storage area.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.getBytesInUse()")}}</dt> + <dd>Gets the amount of storage space (in bytes) used one or more items being stored in the storage area.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.set()")}}</dt> + <dd>Stores one or more items in the storage area. If an item already exists, its value will be updated.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.remove()")}}</dt> + <dd>Removes one or more items from the storage area.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.clear()")}}</dt> + <dd>Removes all items from the storage area.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("webextensions.api.storage.StorageArea")}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/storage#type-StorageArea"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/set/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/set/index.html new file mode 100644 index 0000000000..5201fd64c3 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/storagearea/set/index.html @@ -0,0 +1,90 @@ +--- +title: StorageArea.set() +slug: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/set +translation_of: Mozilla/Add-ons/WebExtensions/API/storage/StorageArea/set +--- +<div>{{AddonSidebar()}}</div> + +<p>저장소 영역에 하나 이상의 항목을 저장하거나, 있는 항목을 고친다.</p> + +<p>이 API로 값을 저장하거나 고치면, {{WebExtAPIRef("storage.onChanged")}} 이벤트가 발생한다.</p> + +<p>비동기 함수로 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>를 돌려준다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">let settingItem = browser.storage.<storageType>.set( + keys // object +) +</pre> + +<p><code><storageType></code>은 쓰기 가능한 저장소 중의 하나다 — {{WebExtAPIRef("storage.sync")}} 또는 {{WebExtAPIRef("storage.local")}}.</p> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>keys</code></dt> + <dd> + <p>저장소에 저장할 하나 이상의 키/값 쌍을 가진 객체다. 이미 있는 항목이라면 그 값은 고쳐진다.</p> + + <p>값은 <a href="/en-US/docs/Glossary/Primitive">기초 자료형</a> (숫자, 논리값, 그리고 문자열 같은) 또는 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">배열</a></code>이다.</p> + + <p><code>Function</code>, <code>Date</code>, <code>RegExp</code>, <code>Set</code>, <code>Map</code>, <code>ArrayBuffer</code> 기타등등 다른 자료형의 저장은 일반적으로 안된다. 지원되지 않는 이런 자료형들은 빈 객체로 저장되거나 에러를 발생시킨다. 정확한 것은 브라우저에 달렸다.</p> + </dd> +</dl> + +<h3 id="반환값">반환값</h3> + +<p>반환된 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>는 동작이 성공하면 아무런 인수없이 완료를 수행하고, 실패하면 에러 문장과 함께 거부를 수행한다.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<p>{{Compat("webextensions.api.storage.StorageArea.set")}}</p> + +<h2 id="예제">예제</h2> + +<pre class="brush: js">function setItem() { + console.log("OK"); +} + +function gotKitten(item) { + console.log(`${item.kitten.name} has ${item.kitten.eyeCount} eyes`); +} + +function gotMonster(item) { + console.log(`${item.monster.name} has ${item.monster.eyeCount} eyes`); +} + +function onError(error) { + console.log(error) +} + +// define 2 objects +var monster = { + name: "Kraken", + tentacles: true, + eyeCount: 10 +} + +var kitten = { + name: "Moggy", + tentacles: false, + eyeCount: 2 +} + +// store the objects +browser.storage.local.set({kitten, monster}) + .then(setItem, onError); + +browser.storage.local.get("kitten") + .then(gotKitten, onError); +browser.storage.local.get("monster") + .then(gotMonster, onError); +</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/storage"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.json</code></a> in the Chromium code.</p> +</div> diff --git a/files/ko/mozilla/add-ons/webextensions/api/storage/sync/index.html b/files/ko/mozilla/add-ons/webextensions/api/storage/sync/index.html new file mode 100644 index 0000000000..37915371f5 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/storage/sync/index.html @@ -0,0 +1,77 @@ +--- +title: storage.sync +slug: Mozilla/Add-ons/WebExtensions/API/storage/sync +translation_of: Mozilla/Add-ons/WebExtensions/API/storage/sync +--- +<div>{{AddonSidebar()}}</div> + +<div> </div> + +<p><code>sync</code> 저장 공간을 의미합니다. <code>sync</code> 저장 공간에 있는 데이터는 브라우저 사이에서 동기화되며 서로 다른 기기 간에 사용자가 브라우저에 로그인 한 경우 언제든지 접근 가능합니다.</p> + +<p>Firefox에서 <code>sync.storage</code> 는 고유한 부가기능 ID에 의존성을 갖고 동작합니다. <code>sync.storage</code>, 를 사용하신다면 <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/applications">어플리케이션</a></code> manifest.json 파일에 있는 키를 통해 여러분의 부가기능에 고유한 ID를 부여해야 합니다.</p> + +<p>이 API는 주로 여러분의 부가기능에 사용자 설정 정보를 저장하고 서로 다른 프로필 간에 설정을 동기화 할 수 있도록 사용됩니다. 이 API는 100KB까지 저장할 수 있습니다. 이보다 더 큰 데이터를 저장하려고 하는 경우, API 요청은 특정한 에러 메시지를 반환할 것입니다. 이 API는 아쉽게도 현재까지 특정한 성능을 보장하진 않습니다.</p> + +<h2 id="메소드">메소드</h2> + +<p><code>sync</code> 객체는 {{WebExtAPIRef("storage.StorageArea")}} 타입에 정의 된 메소드를 제공합니다:</p> + +<dl> + <dt>{{WebExtAPIRef("storage.StorageArea.get()")}}</dt> + <dd>저장소 영역에서 하나 이상의 항목을 가져온다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.getBytesInUse()")}}</dt> + <dd>저장소의 사용된 크기를 바이트단위로 얻는다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.set()")}}</dt> + <dd>저장소에 하나 이상의 항목을 설정한다. 이미 있는 항목은 교체된다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.remove()")}}</dt> + <dd>저장소에서 하나 이상의 값을 지운다.</dd> + <dt>{{WebExtAPIRef("storage.StorageArea.clear()")}}</dt> + <dd>저장소의 모든 항목을 지워서 비운다.</dd> +</dl> + +<h2 id="Browser_호환성">Browser 호환성</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.storage.sync")}}</p> + +<p>{{WebExtExamples}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/storage#property-sync"><code>chrome.storage</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/storage.json"><code>storage.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/tabs/create/index.html b/files/ko/mozilla/add-ons/webextensions/api/tabs/create/index.html new file mode 100644 index 0000000000..1c36ddff1d --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/tabs/create/index.html @@ -0,0 +1,131 @@ +--- +title: tabs.create() +slug: Mozilla/Add-ons/WebExtensions/API/tabs/create +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs/create +--- +<div>{{AddonSidebar()}}</div> + +<p>새 탭을 만든다.</p> + +<p>이것은 비동기 함수로 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>를 돌려준다.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">var creating = browser.tabs.create( + createProperties // object +) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>createProperties</code></dt> + <dd><code>object</code>. 새 탭에 대한 속성들. 속성들에 대해 더 배우려면 {{WebExtAPIRef("tabs.Tab")}} 문서를 보라.</dd> + <dd> + <dl class="reference-values"> + <dt><code>active</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. 활성탭이 되는지를 정한다. 윈도우의 포커스에는 영향이 없다({{WebExtAPIRef('windows.update')}} 참조). 기본값은 <code>true</code>.</dd> + <dt><code>cookieStoreId</code> {{optional_inline}}</dt> + <dd><code>string</code>. 탭의 쿠키 저장 ID를 <code>cookieStoreId</code>로 지정한다. 이 옵션은 확장이 <code>"cookies"</code> <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>을 가져야 쓸 수 있다.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd><code>integer</code>. 윈도우에서 탭의 위치를 지정한다. 쓸 수 있는 값은 0에서 윈도에 있는 탭의 수까지다.</dd> + <dt><code>openerTabId</code>{{optional_inline}}</dt> + <dd><code>integer</code>. The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab.</dd> + <dt><code>openInReaderMode</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. If <code>true</code>, open this tab in <a href="/en-US/Add-ons/WebExtensions/API/tabs/toggleReaderMode">Reader Mode</a>. Defaults to <code>false</code>.</dd> + <dt><code>pinned</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. Whether the tab should be pinned. Defaults to <code>false</code>.</dd> + <dt><code>selected</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. 윈도우에서 탭이 선택되는지를 지정한다. 기본값은 <code>true</code>. + <div class="warning">이 속성은 사용이 중단되었다. 파이어폭스에서는 지원하지 않는다. <code>active</code>가 대신한다.</div> + </dd> + <dt><code>url</code>{{optional_inline}}</dt> + <dd><code>string</code>. 최초 표시될 URL. 기본값은 새 탭 페이지다.</dd> + <dd>URL은 반드시 scheme를 포함해야 한다 (가령은 'http://www.google.com'은 되지만, 'www.google.com'은 안된다).</dd> + <dd>보안상 파이어폭스에서 특권이 있는 URL은 안된다. 그래서 아래와 같은 URL을 주면 실패할 것이다:</dd> + <dd> + <ul> + <li>chrome: URL</li> + <li>javascript: URL</li> + <li>data: URL</li> + <li>file: URL (예, 파일시스템의 파일들. 단, 확장 안에 포함된 파일의 사용은 아래를 보라)</li> + <li>특권이 있는 about: URL (예, <code>about:config</code>, <code>about:addons</code>, <code>about:debugging</code>)<span style="display: none;"> </span>. 특권이 없는 URL은 된다 (예, <code>about:blank</code>).</li> + <li>새 탭 페이지 (<code>about:newtab</code>)는 URL 값이 주어지지 않으면 열린다.</li> + </ul> + + <p>확장에 포함된 페이지의 로딩은 확장의 manifest.json 파일이 있는데서 시작하는 절대 경로를 써라. 예를 들면: '/path/to/my-page.html'. 만약 첫 '/'를 빼면 URL은 상대 경로로 취급되고, 다른 브라우저들은 다른 절대 경로를 생성해낼 것이다.</p> + </dd> + <dt><code>windowId</code>{{optional_inline}}</dt> + <dd><code>integer</code>. 새 탭이 만들어질 윈도우. 기본값은 현재 윈도우.</dd> + </dl> + </dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> that will be fulfilled with a {{WebExtAPIRef('tabs.Tab')}} object containing details about the created tab. If the tab could not be created (for example, because <code>url</code> used a privileged scheme) the promise will be rejected with an error message.</p> + +<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.tabs.create", 10)}}</p> + +<h2 id="예제">예제</h2> + +<p>Open "https://example.org" in a new tab:</p> + +<pre class="brush: js">function onCreated(tab) { + console.log(`Created new tab: ${tab.id}`) +} + +function onError(error) { + console.log(`Error: ${error}`); +} + +browser.browserAction.onClicked.addListener(function() { + var creating = browser.tabs.create({ + url:"https://example.org" + }); + creating.then(onCreated, onError); +});</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/tabs#method-create"><code>chrome.tabs</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json"><code>tabs.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/tabs/index.html b/files/ko/mozilla/add-ons/webextensions/api/tabs/index.html new file mode 100644 index 0000000000..f3a923d31d --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/tabs/index.html @@ -0,0 +1,213 @@ +--- +title: tabs +slug: Mozilla/Add-ons/WebExtensions/API/tabs +tags: + - API + - Add-ons + - Extensions + - Interface + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebExtensions + - tabs +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs +--- +<div>{{AddonSidebar}}</div> + +<p>Interact with the browser's tab system.</p> + +<p>브라우저의 탭 시스템과의 상호작용.</p> + +<p>You can use this API to get a list of opened tabs, filtered by various criteria, and to open, update, move, reload, and remove tabs. You can't directly access the content hosted by tabs using this API, but you can insert JavaScript and CSS into tabs using the {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}} APIs.</p> + +<p>이 API는 열려있는 탭의 목록을 얻는데, 다양한 기준으로 걸러내는데, 그리고 탭을 열고, 고치고, 옮기고, 다시 싣고, 없애는데 사용할 수 있다. 이 API로 탭에 열린 콘텐트를 직접 다룰 수는 없지만, {{WebExtAPIRef("tabs.executeScript()")}}나 {{WebExtAPIRef("tabs.insertCSS()")}} API로 탭에 자바스크립트와 CSS를 끼워 넣을 수는 있다.</p> + +<p>You can use most of this API without any special permission. However:</p> + +<p>특별한 권한없이 이 API의 대부분을 사용할 수 있지만:</p> + +<ul> + <li>to access <code>Tab.url</code>, <code>Tab.title</code>, and <code>Tab.favIconUrl</code>, you need to have the "tabs" <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permission</a>. In Firefox this also means you need "tabs" to {{WebExtAPIRef("tabs.query", "query")}} by URL.</li> + <li>to use {{WebExtAPIRef("tabs.executeScript()")}} or {{WebExtAPIRef("tabs.insertCSS()")}} you must have the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission</a> for the tab</li> +</ul> + +<p> </p> + +<ul> + <li><code>Tab.url</code>, <code>Tab.title</code>, and <code>Tab.favIconUrl</code>에 접근하려면 "tabs" <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>을 가져야 한다. 파이어폭스에서 이 말은 URL로 {{WebExtAPIRef("tabs.query", "query")}} 하는데도 "tabs"가 필요하다는 뜻이다.</li> + <li>{{WebExtAPIRef("tabs.executeScript()")}}나 {{WebExtAPIRef("tabs.insertCSS()")}}를 사용하려면 탭에 대한 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host 권한</a>을 가져야 한다.</li> +</ul> + +<p> </p> + +<p>또는 이런 권한을 일시적으로 얻는 방법도 있다. 현재 활성 탭이거나 명시적인 사용자 동작의 응답이라면 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission">"activeTab" 권한</a>을 요청하면 된다.</p> + +<p>많은 탭 작업은 탭 ID를 사용한다. 탭 ID는 브라우저 세션 내에서 탭마다 고유하도록 보장된다. 브라우저가 다시 시작되면, 탭 ID를 재사용할 수 있고 그럴 것이다. 다시 시작하는 브라우저에 걸쳐서 탭에 정보를 연관시키려면 {{WebExtAPIRef("sessions.setTabValue()")}}를 사용해라.</p> + +<h2 id="Types">Types</h2> + +<dl> + <dt>{{WebExtAPIRef("tabs.MutedInfoReason")}}</dt> + <dd>Specifies the reason a tab was muted or unmuted.</dd> + <dt>{{WebExtAPIRef("tabs.MutedInfo")}}</dt> + <dd>This object contains a boolean indicating whether the tab is muted, and the reason for the last state change.</dd> + <dt>{{WebExtAPIRef("tabs.Tab")}}</dt> + <dd>This type contains information about a tab.</dd> + <dt>{{WebExtAPIRef("tabs.TabStatus")}}</dt> + <dd>Indicates whether the tab has finished loading.</dd> + <dt>{{WebExtAPIRef("tabs.WindowType")}}</dt> + <dd>The type of window that hosts this tab.</dd> + <dt>{{WebExtAPIRef("tabs.ZoomSettingsMode")}}</dt> + <dd>Defines whether zoom changes are handled by the browser, by the add-on, or are disabled.</dd> + <dt>{{WebExtAPIRef("tabs.ZoomSettingsScope")}}</dt> + <dd>Defines whether zoom changes will persist for the page's origin, or only take effect in this tab.</dd> + <dt>{{WebExtAPIRef("tabs.ZoomSettings")}}</dt> + <dd>Defines zoom settings {{WebExtAPIRef("tabs.ZoomSettingsMode", "mode")}}, {{WebExtAPIRef("tabs.ZoomSettingsScope", "scope")}}, and default zoom factor.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{WebExtAPIRef("tabs.TAB_ID_NONE")}}</dt> + <dd>A special ID value given to tabs that are not browser tabs (for example, tabs in devtools windows).</dd> +</dl> + +<h2 id="Functions">Functions</h2> + +<dl> + <dt>{{WebExtAPIRef("tabs.connect()")}}</dt> + <dd>Sets up a messaging connection between the add-on's background scripts (or other privileged scripts, such as popup scripts or options page scripts) and any <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">content scripts</a> running in the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.create()")}}</dt> + <dd>Creates a new tab.</dd> + <dt>{{WebExtAPIRef("tabs.captureVisibleTab()")}}</dt> + <dd>Creates a data URI encoding an image of the visible area of the currently active tab in the specified window.</dd> + <dt>{{WebExtAPIRef("tabs.detectLanguage()")}}</dt> + <dd>Detects the primary language of the content in a tab.</dd> + <dt>{{WebExtAPIRef("tabs.duplicate()")}}</dt> + <dd>Duplicates a tab.</dd> + <dt>{{WebExtAPIRef("tabs.executeScript()")}}</dt> + <dd>Injects JavaScript code into a page.</dd> + <dt>{{WebExtAPIRef("tabs.get()")}}</dt> + <dd>Retrieves details about the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.getAllInWindow()")}} {{deprecated_inline}}</dt> + <dd>Gets details about all tabs in the specified window.</dd> + <dt>{{WebExtAPIRef("tabs.getCurrent()")}}</dt> + <dd>Gets information about the tab that this script is running in, as a <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/Tabs/Tab" title="This type contains information about a tab."><code>tabs.Tab</code></a> object.</dd> + <dt>{{WebExtAPIRef("tabs.getSelected()")}} {{deprecated_inline}}</dt> + <dd>Gets the tab that is selected in the specified window.</dd> + <dt>{{WebExtAPIRef("tabs.getZoom()")}}</dt> + <dd>Gets the current zoom factor of the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.getZoomSettings()")}}</dt> + <dd>Gets the current zoom settings for the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.highlight()")}}</dt> + <dd>Highlights one or more tabs.</dd> + <dt>{{WebExtAPIRef("tabs.insertCSS()")}}</dt> + <dd>Injects CSS into a page.</dd> + <dt>{{WebExtAPIRef("tabs.removeCSS()")}}</dt> + <dd>Removes from a page CSS which was previously injected by calling {{WebExtAPIRef("tabs.insertCSS()")}}.</dd> + <dt>{{WebExtAPIRef("tabs.move()")}}</dt> + <dd>Moves one or more tabs to a new position in the same window or to a different window.</dd> + <dt>{{WebExtAPIRef("tabs.query()")}}</dt> + <dd>Gets all tabs that have the specified properties, or all tabs if no properties are specified.</dd> + <dt>{{WebExtAPIRef("tabs.reload()")}}</dt> + <dd>Reload a tab, optionally bypassing the local web cache.</dd> + <dt>{{WebExtAPIRef("tabs.remove()")}}</dt> + <dd>Closes one or more tabs.</dd> + <dt>{{WebExtAPIRef("tabs.sendMessage()")}}</dt> + <dd>Sends a single message to the content script(s) in the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.sendRequest()")}} {{deprecated_inline}}</dt> + <dd>Sends a single request to the content script(s) in the specified tab. <strong>Deprecated</strong>: use {{WebExtAPIRef("tabs.sendMessage()")}} instead.</dd> + <dt>{{WebExtAPIRef("tabs.setZoom()")}}</dt> + <dd>Zooms the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.setZoomSettings()")}}</dt> + <dd>Sets the zoom settings for the specified tab.</dd> + <dt>{{WebExtAPIRef("tabs.update()")}}</dt> + <dd>Navigate the tab to a new URL, or modify other properties of the tab.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{WebExtAPIRef("tabs.onActivated")}}</dt> + <dd>Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired.</dd> + <dt>{{WebExtAPIRef("tabs.onActiveChanged")}} {{deprecated_inline}}</dt> + <dd>Fires when the selected tab in a window changes. <strong>Deprecated:</strong> use {{WebExtAPIRef("tabs.onActivated")}} instead.</dd> + <dt>{{WebExtAPIRef("tabs.onAttached")}}</dt> + <dd>Fired when a tab is attached to a window, for example because it was moved between windows.</dd> + <dt>{{WebExtAPIRef("tabs.onCreated")}}</dt> + <dd>Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired.</dd> + <dt>{{WebExtAPIRef("tabs.onDetached")}}</dt> + <dd>Fired when a tab is detached from a window, for example because it is being moved between windows.</dd> + <dt>{{WebExtAPIRef("tabs.onHighlightChanged")}} {{deprecated_inline}}</dt> + <dd>Fired when the highlighted or selected tabs in a window change. <strong>Deprecated:</strong> use {{WebExtAPIRef("tabs.onHighlighted")}} instead.</dd> + <dt>{{WebExtAPIRef("tabs.onHighlighted")}}</dt> + <dd>Fired when the highlighted or selected tabs in a window change.</dd> + <dt>{{WebExtAPIRef("tabs.onMoved")}}</dt> + <dd>Fired when a tab is moved within a window.</dd> + <dt>{{WebExtAPIRef("tabs.onRemoved")}}</dt> + <dd>Fired when a tab is closed.</dd> + <dt>{{WebExtAPIRef("tabs.onReplaced")}}</dt> + <dd>Fired when a tab is replaced with another tab due to prerendering.</dd> + <dt>{{WebExtAPIRef("tabs.onSelectionChanged")}} {{deprecated_inline}}</dt> + <dd>Fires when the selected tab in a window changes. <strong>Deprecated:</strong> use {{WebExtAPIRef("tabs.onActivated")}} instead.</dd> + <dt>{{WebExtAPIRef("tabs.onUpdated")}}</dt> + <dd>Fired when a tab is updated.</dd> + <dt>{{WebExtAPIRef("tabs.onZoomChange")}}</dt> + <dd>Fired when a tab is zoomed.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{Compat("webextensions.api.tabs")}}</p> + +<div class="hidden note"> +<p>The "Chrome incompatibilities" section is included from <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities"> https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a> using the <a href="/en-US/docs/Template:WebExtChromeCompat">WebExtChromeCompat</a> macro.</p> + +<p>If you need to update this content, edit <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities">https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities</a>, then shift-refresh this page to see your changes.</p> +</div> + +<h3 id="Edge_incompatibilities">Edge incompatibilities</h3> + +<p>Promises are not supported in Edge. Use callbacks instead.</p> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgements</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/tabs"><code>chrome.tabs</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json"><code>tabs.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/tabs/insertcss/index.html b/files/ko/mozilla/add-ons/webextensions/api/tabs/insertcss/index.html new file mode 100644 index 0000000000..9fbf180263 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/tabs/insertcss/index.html @@ -0,0 +1,129 @@ +--- +title: tabs.insertCSS() +slug: Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS +translation_of: Mozilla/Add-ons/WebExtensions/API/tabs/insertCSS +--- +<div>{{AddonSidebar()}}</div> + +<p>페이지에 CSS 삽입하기</p> + +<p>이 API를 사용하기 위해 여러분은 해당 페이지 URL에 대한 허가가 필요합니다. 이 허가에 대한 요청은 <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">호스트 허가</a>를 통하거나 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission">활성화 된 탭 허가</a>을 사용할 수도 있습니다.</p> + +<p>You can only inject CSS into pages whose URL can be expressed using a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match pattern</a>: meaning, its scheme must be one of "http", "https", "file", "ftp". This means that you can't inject CSS into any of the browser's built-in pages, such as about:debugging, about:addons, or the page that opens when you open a new empty tab.</p> + +<p>The inserted CSS may be removed again by calling {{WebExtAPIRef("tabs.removeCSS()")}}.</p> + +<p>This is an asynchronous function that returns a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code>.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox brush:js">var inserting = browser.tabs.insertCSS( + tabId, // optional integer + details // extensionTypes.InjectDetails +) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>tabId</code> {{optional_inline}}</dt> + <dd><code>integer</code>. The ID of the tab in which to insert the CSS. Defaults to the active tab of the current window.</dd> + <dt><code>details</code></dt> + <dd>{{WebExtAPIRef('extensionTypes.InjectDetails')}}. Describes the CSS to insert. This contains the following properties:</dd> + <dd> + <dl class="reference-values"> + <dt><code>allFrames</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. If <code>true</code>, the CSS will be injected into all frames of the current page. If it is <code>false</code>, CSS is only injected into the top frame. Defaults to <code>false</code>.</dd> + <dt><code>code</code>{{optional_inline}}</dt> + <dd><code>string</code>. Code to inject, as a text string.</dd> + <dt><code>cssOrigin</code>{{optional_inline}}</dt> + <dd><code>string</code>. This can take one of two values: "user", to add the CSS as a user stylesheet, or "author" to add it as an author stylesheet. Specifying "user" enables you to prevent websites from overriding the CSS you insert: see <a href="/en-US/docs/Web/CSS/Cascade#Cascading_order">Cascading order</a>. If this option is omitted, the CSS is added as an author stylesheet.</dd> + <dt><code>file</code>{{optional_inline}}</dt> + <dd><code>string</code>. Path to a file containing the code to inject. In Firefox, relative URLs are resolved relative to the current page URL. In Chrome, these URLs are resolved relative to the add-on's base URL. To work cross-browser, you can specify the path as an absolute URL, starting at the add-on's root, like this: <code>"/path/to/stylesheet.css"</code>.</dd> + <dt><code>frameId</code>{{optional_inline}}</dt> + <dd><code>integer</code>. The frame where the CSS should be injected. Defaults to <code>0</code> (the top-level frame).</dd> + <dt><code>matchAboutBlank</code>{{optional_inline}}</dt> + <dd><code>boolean</code>. If <code>true</code>, the code will be injected into embedded "about:blank" and "about:srcdoc" frames if your add-on has access to their parent document. The code cannot be inserted in top-level about: frames. Defaults to <code>false</code>.</dd> + <dt><code>runAt</code>{{optional_inline}}</dt> + <dd>{{WebExtAPIRef('extensionTypes.RunAt')}}. The soonest that the code will be injected into the tab. Defaults to "document_idle".</dd> + </dl> + </dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> that will be fulfilled with no arguments when all the CSS has been inserted. If any error occurs, the promise will be rejected with an error message.</p> + +<h2 id="Browser_compatibility">Browser compatibility</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.tabs.insertCSS")}}</p> + +<h2 id="Examples">Examples</h2> + +<p>This example inserts into the currently active tab CSS which is taken from a string.</p> + +<pre class="brush: js">var css = "body { border: 20px dotted pink; }"; + +browser.browserAction.onClicked.addListener(() => { + + function onError(error) { + console.log(`Error: ${error}`); + } + + var insertingCSS = browser.tabs.insertCSS({code: css}); + insertingCSS.then(null, onError); +});</pre> + +<p>This example inserts CSS which is loaded from a file packaged with the extension. The CSS is inserted into the tab whose ID is 2:</p> + +<pre class="brush: js">browser.browserAction.onClicked.addListener(() => { + + function onError(error) { + console.log(`Error: ${error}`); + } + + var insertingCSS = browser.tabs.insertCSS(2, {file: "content-style.css"}); + insertingCSS.then(null, onError); +});</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/tabs#method-insertCSS"><code>chrome.tabs</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/api/tabs.json"><code>tabs.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/webrequest/index.html b/files/ko/mozilla/add-ons/webextensions/api/webrequest/index.html new file mode 100644 index 0000000000..3aa39a9590 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/webrequest/index.html @@ -0,0 +1,204 @@ +--- +title: webRequest +slug: Mozilla/Add-ons/WebExtensions/API/webRequest +tags: + - API + - Add-ons + - Extensions + - Interface + - Non-standard + - Reference + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/API/webRequest +--- +<div>{{AddonSidebar}}</div> + +<p>Add event listeners for the various stages of making an HTTP request. The event listener receives detailed information about the request and can modify or cancel the request.</p> + +<p>Each event is fired at a particular stage of the request. The typical sequence of events is like this:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13376/webRequest-flow.png" style="display: block; height: 680px; margin-left: auto; margin-right: auto; width: 624px;"></p> + +<p>{{WebExtAPIRef("webRequest.onErrorOccurred", "onErrorOccurred")}} can be fired at any time during the request. Also, note that sometimes the sequence of events may differ from this: for example, in Firefox, on an <a href="/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security">HSTS</a> upgrade, the <code>onBeforeRedirect</code> event will be triggered immediately after <code>onBeforeRequest</code>.</p> + +<p>All the events, except <code>onErrorOccurred</code>, can take three arguments to <code>addListener()</code>:</p> + +<ul> + <li>the listener itself</li> + <li>a {{WebExtAPIRef("webRequest.RequestFilter", "filter")}} object, so you can only be notified for requests made to particular URLs or for particular types of resource</li> + <li>an optional <code>extraInfoSpec</code> object. You can use this to pass additional event-specific instructions.</li> +</ul> + +<p>리스너는 요청 정보가 담긴 <code>details</code> 객체를 받는다. This includes a request ID, which is provided to enable an add-on to correlate events associated with a single request. It is unique within a browser session and the add-on's context. It stays the same throughout a request, even across redirections and authentication exchanges.</p> + +<p>webRequest API를 사용하려면 확장 프로그램은 "webRequest" <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API 권한</a>을 가져야 하고, 대상 호스트에 대해서도 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">호스트 권한</a>을 가져야 한다. "blocking" 기능을 사용하려면 추가로 "webRequestBlocking" API 권한도 가져야 한다.</p> + +<p>To intercept resources loaded by a page (such as images, scripts, or stylesheets), the extension must have the host permission for the resource as well as for the main page requesting the resource. For example, if a page at "https://developer.mozilla.org" loads an image from "https://mdn.mozillademos.org", then an extension must have both host permissions if it is to intercept the image request.</p> + +<h2 id="Modifying_requests">Modifying requests</h2> + +<p>On some of these events, you can modify the request. Specifically, you can:</p> + +<ul> + <li>cancel the request in: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}</li> + <li>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}</li> + <li>{{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}</li> + </ul> + </li> + <li>redirect the request in: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}}</li> + <li>{{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}</li> + </ul> + </li> + <li>modify request headers in: + <ul> + <li>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} + <ul> + </ul> + </li> + </ul> + </li> + <li>modify response headers in: + <ul> + <li>{{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}}</li> + </ul> + </li> + <li>supply authentication credentials in: + <ul> + <li>{{WebExtAPIRef("webRequest.onAuthRequired", "onAuthRequired")}}</li> + </ul> + </li> +</ul> + +<p>To do this, you need to pass an option with the value "blocking" in the <code>extraInfoSpec</code> argument to the event's <code>addListener()</code>. This makes the listener synchronous. In the listener, you can then return a {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} object, which indicates the modification you need to make: for example, the modified request header you want to send.</p> + +<h2 id="Accessing_security_information">Accessing security information</h2> + +<p>In the {{WebExtAPIRef("webRequest.onHeadersReceived", "onHeadersReceived")}} listener you can access the <a href="/en-US/docs/Glossary/TLS">TLS</a> properties of a request by calling {{WebExtAPIRef("webRequest.getSecurityInfo()", "getSecurityInfo()")}}. To do this you must also pass "blocking" in the <code>extraInfoSpec</code> argument to the event's <code>addListener()</code>.</p> + +<p>You can read details of the TLS handshake, but can't modify them or override the browser's trust decisions.</p> + +<h2 id="Modifying_responses">Modifying responses</h2> + +<p>To modify the HTTP response bodies for a request, call {{WebExtAPIRef("webRequest.filterResponseData")}}, passing it the ID of the request. This returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object that you can use to examine and modify the data as it is received by the browser.</p> + +<p>To do this, you must have the "webRequestBlocking" API permission as well as the "webRequest" <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">API permission</a> and the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#Host_permissions">host permission </a>for the relevant host.</p> + +<h2 id="Types">Types</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.BlockingResponse")}}</dt> + <dd> + <p>An object of this type is returned by event listeners that have set <code>"blocking"</code> in their <code>extraInfoSpec</code> argument. By setting particular properties in <code>BlockingResponse</code>, the listener can modify network requests.</p> + </dd> + <dt>{{WebExtAPIRef("webRequest.CertificateInfo")}}</dt> + <dd>An object describing a single X.509 certificate.</dd> + <dt>{{WebExtAPIRef("webRequest.HttpHeaders")}}</dt> + <dd>An array of HTTP headers. Each header is represented as an object with two properties: <code>name</code> and either <code>value</code> or <code>binaryValue</code>.</dd> + <dt>{{WebExtAPIRef("webRequest.RequestFilter")}}</dt> + <dd>An object describing filters to apply to webRequest events.</dd> + <dt>{{WebExtAPIRef("webRequest.ResourceType")}}</dt> + <dd>Represents a particular kind of resource fetched in a web request.</dd> + <dt>{{WebExtAPIRef("webRequest.SecurityInfo")}}</dt> + <dd>An object describing the security properties of a particular web request.</dd> + <dt>{{WebExtAPIRef("webRequest.StreamFilter")}}</dt> + <dd>An object that can be used to monitor and modify HTTP responses while they are being received.</dd> + <dt>{{WebExtAPIRef("webRequest.UploadData")}}</dt> + <dd>Contains data uploaded in a URL request.</dd> +</dl> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES", "webRequest.MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES")}}</dt> + <dd>The maximum number of times that <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/WebRequest/handlerBehaviorChanged" title="Suppose an add-on's job is to block web requests against a pattern, and the following scenario happens:"><code>handlerBehaviorChanged()</code></a></code> can be called in a 10 minute period.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.handlerBehaviorChanged()")}}</dt> + <dd>This method can be used to ensure that event listeners are applied correctly when pages are in the browser's in-memory cache.</dd> + <dt>{{WebExtAPIRef("webRequest.filterResponseData()")}}</dt> + <dd>Returns a {{WebExtAPIRef("webRequest.StreamFilter")}} object for a given request.</dd> + <dt>{{WebExtAPIRef("webRequest.getSecurityInfo()")}}</dt> + <dd>Gets detailed information about the <a href="/en-US/docs/Glossary/TLS">TLS</a> connection associated with a given request.</dd> +</dl> + +<h2 id="Events">Events</h2> + +<dl> + <dt>{{WebExtAPIRef("webRequest.onBeforeRequest")}}</dt> + <dd>Fired when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.</dd> + <dt>{{WebExtAPIRef("webRequest.onBeforeSendHeaders")}}</dt> + <dd>Fired before sending any HTTP data, but after HTTP headers are available. This is a good place to listen if you want to modify HTTP request headers.</dd> + <dt>{{WebExtAPIRef("webRequest.onSendHeaders")}}</dt> + <dd>Fired just before sending headers. If your add-on or some other add-on modified headers in <code>{{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}}</code>, you'll see the modified version here.</dd> + <dt>{{WebExtAPIRef("webRequest.onHeadersReceived")}}</dt> + <dd>Fired when the HTTP response headers associated with a request have been received. You can use this event to modify HTTP response headers.</dd> + <dt>{{WebExtAPIRef("webRequest.onAuthRequired")}}</dt> + <dd>Fired when the server asks the client to provide authentication credentials. The listener can do nothing, cancel the request, or supply authentication credentials.</dd> + <dt>{{WebExtAPIRef("webRequest.onResponseStarted")}}</dt> + <dd>Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.</dd> + <dt>{{WebExtAPIRef("webRequest.onBeforeRedirect")}}</dt> + <dd>Fired when a server-initiated redirect is about to occur.</dd> + <dt>{{WebExtAPIRef("webRequest.onCompleted")}}</dt> + <dd>Fired when a request is completed.</dd> + <dt>{{WebExtAPIRef("webRequest.onErrorOccurred")}}</dt> + <dd>Fired when an error occurs.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("webextensions.api.webRequest")}}</p> + +<p> </p> + +<p><a href="/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#webRequest_incompatibilities">Extra notes on Chrome incompatibilities</a>.</p> + +<p> </p> + +<p>{{WebExtExamples("h2")}}</p> + +<div class="note"><strong>Acknowledgments</strong> + +<p>This API is based on Chromium's <a href="https://developer.chrome.com/extensions/webRequest"><code>chrome.webRequest</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.json"><code>web_request.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/api/webrequest/onbeforerequest/index.html b/files/ko/mozilla/add-ons/webextensions/api/webrequest/onbeforerequest/index.html new file mode 100644 index 0000000000..ecc9e9be39 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/api/webrequest/onbeforerequest/index.html @@ -0,0 +1,239 @@ +--- +title: webRequest.onBeforeRequest +slug: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest +translation_of: Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest +--- +<div>{{AddonSidebar()}}</div> + +<p>This event is triggered when a request is about to be made, and before headers are available. This is a good place to listen if you want to cancel or redirect the request.</p> + +<p>To cancel or redirect the request, first include <code>"blocking"</code> in the <code>extraInfoSpec</code> array argument to <code>addListener()</code>. Then, in the listener function, return a {{WebExtAPIRef("webRequest.BlockingResponse", "BlockingResponse")}} object, setting the appropriate property:</p> + +<ul> + <li>to cancel the request, include a property <code>cancel</code> with the value <code>true</code>.</li> + <li>to redirect the request, include a property <code>redirectUrl</code> with the value set to the URL to which you want to redirect.</li> +</ul> + +<p>From Firefox 52 onwards, instead of returning <code>BlockingResponse</code>, the listener can return a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> which is resolved with a <code>BlockingResponse</code>. This enables the listener to process the request asynchronously.</p> + +<p>If you use <code>"blocking"</code>, you must have the <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#API_permissions">"webRequestBlocking" API permission</a> in your manifest.json.</p> + +<h2 id="문법">문법</h2> + +<pre class="syntaxbox brush:js">browser.webRequest.onBeforeRequest.addListener( + listener, // function + filter, // object + extraInfoSpec // optional array of strings +) +browser.webRequest.onBeforeRequest.removeListener(listener) +browser.webRequest.onBeforeRequest.hasListener(listener) +</pre> + +<p>Events have three functions:</p> + +<dl> + <dt><code>addListener(callback, filter, extraInfoSpec)</code></dt> + <dd>Adds a listener to this event.</dd> + <dt><code>removeListener(listener)</code></dt> + <dd>Stop listening to this event. The <code>listener</code> argument is the listener to remove.</dd> + <dt><code>hasListener(listener)</code></dt> + <dd>Check whether <code>listener</code> is registered for this event. Returns <code>true</code> if it is listening, <code>false</code> otherwise.</dd> +</dl> + +<h2 id="리스너_등록_문법">리스너 등록 문법</h2> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>callback</code></dt> + <dd> + <p>Function that will be called when this event occurs. The function will be passed the following arguments:</p> + + <dl class="reference-values"> + <dt><code>details</code></dt> + <dd><a href="#details"><code>object</code></a>. Details about the request. See <code><a href="#details">details</a></code> below.</dd> + </dl> + + <p>Returns: {{WebExtAPIRef('webRequest.BlockingResponse')}}. If <code>"blocking"</code> is specified in the <code>extraInfoSpec</code> parameter, the event listener should return a <code>BlockingResponse</code> object, and can set either its <code>cancel</code> or its <code>redirectUrl</code> properties. From Firefox 52 onwards, instead of returning <code>BlockingResponse</code>, the listener can return a <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> which is resolved with a <code>BlockingResponse</code>. This enables the listener to process the request asynchronously.</p> + </dd> + <dt><code>filter</code></dt> + <dd>{{WebExtAPIRef('webRequest.RequestFilter')}}. A filter that restricts the events that will be sent to this listener.</dd> + <dt><code>extraInfoSpec</code>{{optional_inline}}</dt> + <dd><code>array</code> of <code>string</code>. <span class="im">Extra options for the event. You can pass any of the following values:</span></dd> + <dd> + <ul> + <li><code>"blocking"</code>: make the request synchronous, so you can cancel or redirect the request</li> + <li><span class="im"><code>"requestBody"</code>: include <code>requestBody</code> in the <code>details</code> object passed to the listener</span></li> + </ul> + </dd> +</dl> + +<h2 id="추가적인_객체">추가적인 객체</h2> + +<h3 id="details">details</h3> + +<dl class="reference-values"> + <dt><code>requestId</code></dt> + <dd><code>string</code>. The ID of the request. Request IDs are unique within a browser session, so you can use them to relate different events associated with the same request.</dd> + <dt><code>url</code></dt> + <dd><code>string</code>. Target of the request.</dd> + <dt><code>method</code></dt> + <dd><code>string</code>. Standard HTTP method: for example, "GET" or "POST".</dd> + <dt><code>frameId</code></dt> + <dd><code>integer</code>. Zero if the request happens in the main frame; a positive value is the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (<code>type</code> is <code>main_frame</code> or <code>sub_frame</code>), <code>frameId</code> indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab.</dd> + <dt><code>parentFrameId</code></dt> + <dd><code>integer</code>. ID of the frame that contains the frame which sent the request. Set to -1 if no parent frame exists.</dd> + <dt><code>requestBody</code>{{optional_inline}}</dt> + <dd><code>object</code>. Contains the HTTP request body data. Only provided if <code>extraInfoSpec</code> contains <code>"requestBody"</code>.</dd> + <dd> + <dl class="reference-values"> + <dt><code>error</code>{{optional_inline}}</dt> + <dd><code>string</code>. This is set if any errors were encountered when obtaining request body data.</dd> + <dt><code>formData</code>{{optional_inline}}</dt> + <dd><code>object</code>. This object is present if the request method is POST and the body is a sequence of key-value pairs encoded in UTF-8 as either "multipart/form-data" or "application/x-www-form-urlencoded".</dd> + <dd>It is a dictionary in which each key contains the list of all values for that key. For example: <code>{'key': ['value1', 'value2']}</code>. If the data is of another media type, or if it is malformed, the object is not present.</dd> + <dt><code>raw</code>{{optional_inline}}</dt> + <dd><code>array</code> of <code>{{WebExtAPIRef('webRequest.UploadData')}}</code>. If the request method is PUT or POST, and the body is not already parsed in <code>formData</code>, then this array contains the unparsed request body elements.</dd> + </dl> + </dd> + <dt><code>tabId</code></dt> + <dd><code>integer</code>. ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab.</dd> + <dt><code>type</code></dt> + <dd>{{WebExtAPIRef('webRequest.ResourceType')}}. The type of resource being requested: for example, "image", "script", "stylesheet".</dd> + <dt><code>timeStamp</code></dt> + <dd><code>number</code>. The time when this event fired, in <a href="https://en.wikipedia.org/wiki/Unix_time">milliseconds since the epoch</a>.</dd> + <dt><code>originUrl</code></dt> + <dd><code>string</code>. URL of the resource that triggered this request. Note that this may not be the same as the URL of the page into which the requested resource will be loaded. For example, if a document triggers a load in a different window through the <a href="/en-US/docs/Web/HTML/Element/a#attr-target">target attribute of a link</a>, or a CSS document includes an image using the <a href="/en-US/docs/Web/CSS/url#The_url()_functional_notation"><code>url()</code> functional notation</a>, then this will be the URL of the original document or of the CSS document, respectively.</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.webRequest.onBeforeRequest", 10)}}</p> + +<h2 id="예제">예제</h2> + +<p>This code logs the URL for every resource requested which matches the <a href="/en-US/Add-ons/WebExtensions/Match_patterns#<all_urls>"><all_urls></a> pattern:</p> + +<pre class="brush: js">function logURL(requestDetails) { + console.log("Loading: " + requestDetails.url); +} + +browser.webRequest.onBeforeRequest.addListener( + logURL, + {urls: ["<all_urls>"]} +);</pre> + +<p>This code cancels requests for images that are made to URLs under "https://mdn.mozillademos.org/" (to see the effect, visit any page on MDN that contains images, such as <a href="/en-US/docs/Mozilla/Firefox/Developer_Edition">Firefox Developer Edition</a>):</p> + +<pre class="brush: js">// match pattern for the URLs to redirect +var pattern = "https://mdn.mozillademos.org/*"; + +// cancel function returns an object +// which contains a property `cancel` set to `true` +function cancel(requestDetails) { + console.log("Canceling: " + requestDetails.url); + return {cancel: true}; +} + +// add the listener, +// passing the filter argument and "blocking" +browser.webRequest.onBeforeRequest.addListener( + cancel, + {urls: [pattern], types: ["image"]}, + ["blocking"] +); +</pre> + +<p>This code replaces, by redirection, all network requests for images that are made to URLs under "https://mdn.mozillademos.org/" (to see the effect, visit any page on MDN that contains images, such as <a href="/en-US/docs/Mozilla/Firefox/Developer_Edition">Firefox Developer Edition</a>):</p> + +<pre class="brush: js">// match pattern for the URLs to redirect +var pattern = "https://mdn.mozillademos.org/*"; + +// redirect function +// returns an object with a property `redirectURL` +// set to the new URL +function redirect(requestDetails) { + console.log("Redirecting: " + requestDetails.url); + return { + redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif" + }; +} + +// add the listener, +// passing the filter argument and "blocking" +browser.webRequest.onBeforeRequest.addListener( + redirect, + {urls:[pattern], types:["image"]}, + ["blocking"] +);</pre> + +<p>This code is exactly like the previous example, except that the listener handles the request asynchronously. It returns a <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a></code> that sets a timer, and resolves with the redirect URL when the timer expires:</p> + +<pre class="brush: js">// match pattern for the URLs to redirect +var pattern = "https://mdn.mozillademos.org/*"; + +// URL we will redirect to +var redirectUrl = "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"; + +// redirect function returns a Promise +// which is resolved with the redirect URL when a timer expires +function redirectAsync(requestDetails) { + console.log("Redirecting async: " + requestDetails.url); + var asyncCancel = new Promise((resolve, reject) => { + window.setTimeout(() => { + resolve({redirectUrl}); + }, 2000); + }); + + return asyncCancel; +} + +// add the listener, +// passing the filter argument and "blocking" +browser.webRequest.onBeforeRequest.addListener( + redirectAsync, + {urls: [pattern], types: ["image"]}, + ["blocking"] +);</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/webRequest#event-onBeforeRequest"><code>chrome.webRequest</code></a> API. This documentation is derived from <a href="https://chromium.googlesource.com/chromium/src/+/master/extensions/common/api/web_request.json"><code>web_request.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>// 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> diff --git a/files/ko/mozilla/add-ons/webextensions/content_scripts/index.html b/files/ko/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..7d1c49e05a --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,479 @@ +--- +title: Content scripts +slug: Mozilla/Add-ons/WebExtensions/Content_scripts +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +<div>{{AddonSidebar}}</div> + +<p>A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the web site itself, such as those loaded using the {{HTMLElement("script")}} element).</p> + +<p><a href="/en-US/Add-ons/WebExtensions/Background_scripts">Background scripts</a> can access all the <a href="/en-US/Add-ons/WebExtensions/API">WebExtension JavaScript APIs</a>, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.</p> + +<p>Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.</p> + +<p>Content scripts can only access <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#WebExtension_APIs">a small subset of the WebExtension APIs</a>, but they can <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_scripts#Communicating_with_background_scripts">communicate with background scripts</a> using a messaging system, and thereby indirectly access the WebExtension APIs.</p> + +<div class="note"> +<p>Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a <a href="/en-US/docs/Web/HTTP/CSP">CSP</a> error.</p> + +<p>As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/onboarding_upboarding_offboarding_best_practices">onboarding page</a> that moves users away from addons.mozilla.org.</p> +</div> + +<div class="note"> +<p>Values added to the global scope of a content script with <code>var foo</code> or <code>window.foo = "bar"</code> may disappear due to bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1408996">1408996</a>.</p> +</div> + +<h2 id="Loading_content_scripts">Loading content scripts</h2> + +<p>You can load a content script into a web page in one of three ways:</p> + +<ol> + <li><strong>at install time, into pages that match URL patterns:</strong> using the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts">content_scripts</a></code> key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Match_patterns">matches a given pattern</a>.</li> + <li><strong>at runtime, into pages that match URL patterns:</strong> using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Match_patterns">matches a given pattern</a>. This is just like method (1), except you can add and remove content scripts at runtime.</li> + <li><strong>at runtime, into specific tabs:</strong> using the <code><a href="/en-US/Add-ons/WebExtensions/API/Tabs/executeScript">tabs.executeScript()</a></code> API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_action">browser action</a>.</li> +</ol> + +<p>There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.</p> + +<p>Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match pattern</a>. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".</p> + +<h2 id="Content_script_environment">Content script environment</h2> + +<h3 id="DOM_access">DOM access</h3> + +<p>Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.</p> + +<p>However, content scripts get a "clean view of the DOM". This means:</p> + +<ul> + <li>content scripts cannot see JavaScript variables defined by page scripts</li> + <li>if a page script redefines a built-in DOM property, the content script will see the original version of the property, not the redefined version.</li> +</ul> + +<p>In Gecko, this behavior is called <a href="/en-US/docs/Xray_vision">Xray vision</a>.</p> + +<p>For example, consider a web page like this:</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + </head> + + <body> + <script src="page-scripts/page-script.js"></script> + </body> +</html></pre> + +<p>The script "page-script.js" does this:</p> + +<pre class="brush: js">// page-script.js + +// add a new element to the DOM +var p = document.createElement("p"); +p.textContent = "This paragraph was added by a page script."; +p.setAttribute("id", "page-script-para"); +document.body.appendChild(p); + +// define a new property on the window +window.foo = "This global variable was added by a page script"; + +// redefine the built-in window.confirm() function +window.confirm = function() { + alert("The page script has also redefined 'confirm'"); +}</pre> + +<p>Now an extension injects a content script into the page:</p> + +<pre class="brush: js">// content-script.js + +// can access and modify the DOM +var pageScriptPara = document.getElementById("page-script-para"); +pageScriptPara.style.backgroundColor = "blue"; + +// can't see page-script-added properties +console.log(window.foo); // undefined + +// sees the original form of redefined properties +window.confirm("Are you sure?"); // calls the original window.confirm()</pre> + +<p>The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.</p> + +<p>All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.</p> + +<p>One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.</p> + +<p>If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:</p> + +<pre class="brush: json">"content_scripts": [ + { + "matches": ["*://*.mozilla.org/*"], + "js": ["jquery.js", "content-script.js"] + } +]</pre> + +<p>Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts">Sharing objects with page scripts</a> for more details.</p> + +<h3 id="WebExtension_APIs">WebExtension APIs</h3> + +<p>In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:</p> + +<p>From <code><a href="/en-US/Add-ons/WebExtensions/API/extension">extension</a></code>:</p> + +<ul> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/extension#getURL()">getURL()</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/extension#inIncognitoContext">inIncognitoContext</a></code></li> +</ul> + +<p>From <code><a href="/en-US/Add-ons/WebExtensions/API/runtime">runtime</a></code>:</p> + +<ul> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#connect()">connect()</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#getManifest()">getManifest()</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#getURL()">getURL()</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#onConnect">onConnect</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#onMessage">onMessage</a></code></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/runtime#sendMessage()">sendMessage()</a></code></li> +</ul> + +<p>From <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n">i18n</a></code>:</p> + +<ul> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/getMessage">getMessage()</a></code></li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/getAcceptLanguages">getAcceptLanguages()</a></code></li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/getUILanguage">getUILanguage()</a></code></li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/i18n/detectLanguage">detectLanguage()</a></code></li> +</ul> + +<p>From <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus">menus</a></code>:</p> + +<ul> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/menus/getTargetElement">getTargetElement</a></code></li> +</ul> + +<p>Everything from <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage">storage</a></code>.</p> + +<h3 id="XHR_and_Fetch">XHR and Fetch</h3> + +<p>Content scripts can make requests using the normal <code><a href="/en-US/docs/Web/API/XMLHttpRequest">window.XMLHttpRequest</a></code> and <code><a href="/en-US/docs/Web/API/Fetch_API">window.fetch()</a></code> APIs.</p> + +<p>Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the <code><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/permissions">permissions</a></code> key in manifest.json, then its content scripts get access that domain as well.</p> + +<p>This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the <code><a href="/en-US/docs/Web/HTTP/Headers/Origin">Origin</a></code> and <code><a href="/en-US/docs/Web/HTTP/Headers/Referer">Referer</a></code> headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use <code>content.XMLHttpRequest</code> and <code>content.fetch()</code> instead. For cross-browser extensions their presence must be feature-detected.</p> + +<h2 id="Communicating_with_background_scripts">Communicating with background scripts</h2> + +<p>Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.</p> + +<p>There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.</p> + +<h3 id="One-off_messages">One-off messages</h3> + +<p>To send one-off messages, with an optional response, you can use the following APIs:</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="row"> </th> + <th scope="col">In content script</th> + <th scope="col">In background script</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">Send a message</th> + <td><code><a href="/en-US/Add-ons/WebExtensions/API/runtime/sendMessage">browser.runtime.sendMessage()</a></code></td> + <td><code><a href="/en-US/Add-ons/WebExtensions/API/Tabs/sendMessage">browser.tabs.sendMessage()</a></code></td> + </tr> + <tr> + <th scope="row">Receive a message</th> + <td><code><a href="/en-US/Add-ons/WebExtensions/API/runtime/onMessage">browser.runtime.onMessage</a></code></td> + <td><code><a href="/en-US/Add-ons/WebExtensions/API/runtime/onMessage">browser.runtime.onMessage</a></code></td> + </tr> + </tbody> +</table> + +<p>For example, here's a content script which listens for click events in 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="/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> + +<p>This example code is lightly adapted from the <a href="https://github.com/mdn/webextensions-examples/tree/master/notify-link-clicks-i18n">notify-link-clicks-i18n</a> example on GitHub.</p> + +<h3 id="Connection-based_messaging">Connection-based messaging</h3> + +<p>Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.</p> + +<p>Each side has a <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port">runtime.Port</a></code> object, which they can use to exchange messages.</p> + +<p>To create the connection:</p> + +<ul> + <li>one side listens for connections using <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onConnect">runtime.onConnect</a></code></li> + <li>the other side calls either <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/connect">tabs.connect()</a></code> (if connecting to a content script) or <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/connect">runtime.connect()</a></code> (if connecting to a background script). This returns a <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port">runtime.Port</a></code> object.</li> + <li>the <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onConnect">runtime.onConnect</a></code> listener gets passed its own <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/Port">runtime.Port</a></code> object.</li> +</ul> + +<p>Once each side has a port, the two sides can exchange messages using <code>runtime.Port.postMessage()</code> to send a message, and <code>runtime.Port.onMessage</code> to receive messages.</p> + +<p>For example, as soon as it loads, this content script:</p> + +<ul> + <li>connects to the background script, and stores the <code>Port</code> in a variable <code>myPort</code></li> + <li>listens for messages on <code>myPort</code>, and logs them</li> + <li>sends messages to the background script, using <code>myPort</code>, when the user clicks the document</li> +</ul> + +<pre class="brush: js">// content-script.js + +var myPort = browser.runtime.connect({name:"port-from-cs"}); +myPort.postMessage({greeting: "hello from content script"}); + +myPort.onMessage.addListener(function(m) { + console.log("In content script, received message from background script: "); + console.log(m.greeting); +}); + +document.body.addEventListener("click", function() { + myPort.postMessage({greeting: "they clicked the page!"}); +});</pre> + +<p>The corresponding background script:</p> + +<ul> + <li>listens for connection attempts from the content script</li> + <li>when it receives a connection attempt: + <ul> + <li>stores the port in a variable named <code>portFromCS</code></li> + <li>sends the content script a message using the port</li> + <li>starts listening to messages received on the port, and logs them</li> + </ul> + </li> + <li>sends messages to the content script, using <code>portFromCS</code>, when the user clicks the extension's browser action</li> +</ul> + +<pre class="brush: js">// background-script.js + +var portFromCS; + +function connected(p) { + portFromCS = p; + portFromCS.postMessage({greeting: "hi there content script!"}); + portFromCS.onMessage.addListener(function(m) { + console.log("In background script, received message from content script") + console.log(m.greeting); + }); +} + +browser.runtime.onConnect.addListener(connected); + +browser.browserAction.onClicked.addListener(function() { + portFromCS.postMessage({greeting: "they clicked the button!"}); +}); +</pre> + +<h4 id="Multiple_content_scripts">Multiple content scripts</h4> + +<p>If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.</p> + +<p> </p> + +<ul> +</ul> + +<pre class="brush: js">// background-script.js + +var ports = [] + +function connected(p) { + ports[p.sender.tab.id] = p + //... +} + +browser.runtime.onConnect.addListener(connected) + +browser.browserAction.onClicked.addListener(function() { + ports.forEach(p => { + p.postMessage({greeting: "they clicked the button!"}) + }) +});</pre> + +<p> </p> + +<ul> +</ul> + +<h2 id="Communicating_with_the_web_page">Communicating with the web page</h2> + +<p>Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM <code><a href="/en-US/docs/Web/API/Window/postMessage">window.postMessage</a></code> and <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">window.addEventListener</a></code> APIs.</p> + +<p>콘텐트 스크립트는 기본적으로 페이지 스크립트가 만든 객체에 접근할 수 없지만, DOM의 <code><a href="/en-US/docs/Web/API/Window/postMessage">window.postMessage</a></code>와 <code><a href="/en-US/docs/Web/API/EventTarget/addEventListener">window.addEventListener</a></code> API로 페이지 스크립트와 소통할 수 있다.</p> + +<p>For example:</p> + +<p>예를 들어:</p> + +<pre class="brush: js">// page-script.js + +var messenger = document.getElementById("from-page-script"); + +messenger.addEventListener("click", messageContentScript); + +function messageContentScript() { + window.postMessage({ + direction: "from-page-script", + message: "Message from the page" + }, "*");</pre> + +<pre class="brush: js">// content-script.js + +window.addEventListener("message", function(event) { + if (event.source == window && + event.data && + event.data.direction == "from-page-script") { + alert("Content script received message: \"" + event.data.message + "\""); + } +});</pre> + +<p>For a complete working example of this, <a href="https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html">visit the demo page on GitHub</a> and follow the instructions.</p> + +<p>이에 대한 완전한 예제를 보려면 <a href="https://mdn.github.io/webextensions-examples/content-script-page-script-messaging.html">GitHub의 데모페이지</a>를 방문하여 지침을 따르십시오.</p> + +<div class="warning"> +<p>Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.</p> + +<p>이런 방식으로 신뢰할 수 없는 웹 콘텐트와 상호 작용할 때마다 매우 조심해야한다. 확장 기능은 강력한 기능을 제공 할 수 있는 권한있는 코드이며 적대적인 웹 페이지는 이러한 기능에 접근하는 부분을 쉽게 속일 수 있다.</p> + +<p>To make a trivial example, suppose the content script code that receives the message does something like this:</p> + +<p>간단한 예제로, 콘텐트 스크립트가 아래처럼 동작하는 메시지를 받는다고 한다면:</p> + +<pre class="brush: js">// content-script.js + +window.addEventListener("message", function(event) { + if (event.source == window && + event.data.direction && + event.data.direction == "from-page-script") { + eval(event.data.message); + } +});</pre> + +<p>Now the page script can run any code with all the privileges of the content script.</p> + +<p>이제 페이지 스크립트는 콘텐트 스크립트의 권한으로 어떤 코드라도 실행할 수 있게 된다.</p> +</div> + +<h2 id="Using_eval_in_content_scripts">Using eval() in content scripts</h2> + +<p>In Chrome, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a></code> always runs code in the context of the content script, not in the context of the page.</p> + +<p>크롬에서, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a></code>은 항상 콘텐트 스크립트의 컨텍스트에서 코드를 실행한다. 페이지의 컨텍스트에서 하지 않는다.</p> + +<p>In Firefox:</p> + +<ul> + <li>if you call <code>eval()</code>, it runs code in the context of the content script</li> + <li>if you call <code>window.eval()</code>, it runs code in the context of the page.</li> +</ul> + +<p><span>파이어폭스</span>에서:</p> + +<ul> + <li><code>eval()</code>을 호출하면, 콘텐트 스크립트의 컨텍스트에서 코드를 실행한다.</li> + <li><code>window.eval()</code>을 호출하면, 페이지의 컨텍스트에서 코드를 실행한다.</li> +</ul> + +<p>For example, consider a content script like this:</p> + +<p>예를 들어, 콘텐트 스크립트가 아래 같다고 한다면:</p> + +<pre class="brush: js">// content-script.js + +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" +}, "*");</pre> + +<p>This code just creates some variables x and y using <code>window.eval()</code> and <code>eval()</code>, then logs their values, then messages the page.</p> + +<p>이 코드는 <code>window.eval()</code> 및 <code>eval()</code>을 사용하여 변수 x 및 y를 만든 다음 값의 로그를 남기고, 페이지에 메시지를 보낸다.</p> + +<p>On receiving the message, the page script logs the same variables:</p> + +<p>그 메세지를 받으면, 페이지 스크립트는 같은 변수들을 로그에 남긴다:</p> + +<pre class="brush: js">window.addEventListener("message", function(event) { + if (event.source === window && event.data && event.data.message === "check") { + console.log(`In page script, window.x: ${window.x}`); + console.log(`In page script, window.y: ${window.y}`); + } +});</pre> + +<p>In Chrome, this will produce output like this:</p> + +<p>크롬에서, 이것은 아래처럼 출력될 것이다:</p> + +<pre>In content script, window.x: 1 +In content script, window.y: 2 +In page script, window.x: undefined +In page script, window.y: undefined</pre> + +<p>In Firefox the following output is produced:</p> + +<p>파이어폭스에서는 아래의 출력이 만들어진다:</p> + +<pre>In content script, window.x: undefined +In content script, window.y: 2 +In page script, window.x: 1 +In page script, window.y: undefined</pre> + +<p>The same applies to <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout()</a></code>, <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval">setInterval()</a></code>, and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function()</a></code>.</p> + +<p>같은 것이 <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout">setTimeout()</a></code>, <code><a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval">setInterval()</a></code>, 그리고 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function">Function()</a></code>에 적용된다.</p> + +<p>When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:</p> + +<p>페이지 컨텍스트에서 코드를 실행할 때는 매우 주의해야 한다. 페이지의 환경은 잠재적으로 악의적인 웹 페이지에 의해 제어되며, 상호 작용하는 객체가 예기치 않은 방식으로 재정의될 수 있다.</p> + +<pre class="brush: js">// page.js redefines console.log + +var original = console.log; + +console.log = function() { + original(true); +} +</pre> + +<pre class="brush: js">// content-script.js calls the redefined version + +window.eval('console.log(false)'); +</pre> diff --git a/files/ko/mozilla/add-ons/webextensions/examples/index.html b/files/ko/mozilla/add-ons/webextensions/examples/index.html new file mode 100644 index 0000000000..1f613232bb --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/examples/index.html @@ -0,0 +1,22 @@ +--- +title: Example extensions +slug: Mozilla/Add-ons/WebExtensions/Examples +translation_of: Mozilla/Add-ons/WebExtensions/Examples +--- +<div>{{AddonSidebar}}</div> + +<p><span class="translation">확장앱 개발하는 방법을 설명하기 위해 간단한 예제를 저장해놓은 저장소를 두고 있다</span> <a href="https://github.com/mdn/webextensions-examples">https://github.com/mdn/webextensions-examples</a>. <span class="translation">이번장에서는 해당 저장소에서 사용되는 WebExtension API에 대해 설명한다.</span></p> + +<p>여기에 나오는 예제는 Firefox Nightly에서 동작한다. 대부분은 이전 버전에서도 동작하지만 <span class="translation">확장앱의 manifest.json에서 </span><a href="/en-US/Add-ons/WebExtensions/manifest.json/applications">strict_min_version</a><span class="translation"> 키를 확인한다.</span></p> + +<p><span class="translation">이 예제를 실행해보려면 세가지 방법이 있다</span>.</p> + +<ol> + <li>레파지토리를 클론한뒤 소스 디렉토리를 <a href="/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">"Load Temporary Add-on"</a>기능으로 로드한다. 확장앱은 Firefox를 재시작하기 전까지 로드되어있다.</li> + <li>레파지토리를 클론한뒤 <a href="/en-US/Add-ons/WebExtensions/Getting_started_with_web-ext">web-ext</a> 커멘드 라인 툴을 이용해서 확장앱을 Firefox에 설치한다.</li> + <li>레파지토리를 클론한뒤 <a href="https://github.com/mdn/webextensions-examples/tree/master/build">빌드</a> 디렉토리로 이동한다. <span class="translation">여기에는 빌드된 예제들이 있으므로 Firefox에서 (파일 / 파일 열기를 사용해) 파일을 열고 </span><a href="https://addons.mozilla.org/en-US/firefox/">addons.mozilla.org</a><span class="translation">에서 설치하는것 처럼 영구적으로 설치할 수 있습니다.</span></li> +</ol> + +<p>레파지토리에 공헌하려한다면 <a href="https://github.com/mdn/webextensions-examples/blob/master/CONTRIBUTING.md">pull request를 보내면 된다</a></p> + +<p>{{WebExtAllExamples}}</p> diff --git a/files/ko/mozilla/add-ons/webextensions/index.html b/files/ko/mozilla/add-ons/webextensions/index.html new file mode 100644 index 0000000000..2d5d0117d8 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/index.html @@ -0,0 +1,143 @@ +--- +title: WebExtensions +slug: Mozilla/Add-ons/WebExtensions +tags: + - 확장기능 +translation_of: Mozilla/Add-ons/WebExtensions +--- +<div> +<div>{{AddonSidebar}}</div> + +<p>Extension(이하 확장기능)은 브라우저의 기능을 확장하고 수정할 수 있습니다. Firefox 를 위한 확장기능은 확장 기능 개발을 위한 크로스 브라우저 시스템인 WebExtension API를 이용하여 만들어졌습니다. 이 시스템은 Google Chrome, Opera 및 <a href="https://browserext.github.io/browserext/">W3C Draft Community Group</a>에서 지원하는 <a class="external-icon external" href="https://developer.chrome.com/extensions">extension API</a> 와 대부분 호환됩니다. 그러므로 Google Chrome과 Opera를 대상으로 만들어진 확장기능은 <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Porting_from_Google_Chrome">조금만 수정</a>하면 대부분 Firefox나 <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/extensions/">Microsoft Edge</a>에서도 동작합니다. 또한 extension API는 <a href="https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox">멀티프로세스 Firefox</a>와도 완벽하게 호환됩니다.</p> + +<p> </p> + +<p>질문 혹은 아이디어가 있거나, 기존 Extension을 WebExtensions API로 마이그레이션 할 때 도움이 필요하다면 <a href="https://mail.mozilla.org/listinfo/dev-addons" rel="noopener">dev-addons 메일링 리스트</a>나 <a href="https://wiki.mozilla.org/IRC" rel="noopener">IRC</a>의 <a href="irc://irc.mozilla.org/webextensions">#webextensions</a>를 통해 알려주세요. </p> +</div> + +<p> </p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 id="시작하기">시작하기</h2> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/What_are_WebExtensions">확장기능이란 무엇인가?</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Your_first_WebExtension">첫번째 확장기능</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Your_second_WebExtension">두번째 확장기능</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension">확장기능의 구조</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Firefox_workflow_overview">파이어폭스 개발 로드맵</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Examples">확장기능의 예시</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/What_next_">그 다음은?</a></li> +</ul> + +<h2 id="개념">개념</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API">JavaScript API 일람</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Content_scripts">Content scripts</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Match_patterns">주소패턴</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files">파일과 상호작용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization">여러 언어로 제공하기 </a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Security_best_practices">보안 유의사항들</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">보안 정책</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging">다른 프로그램과 상호작용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Using_the_devtools_APIs">개발자 도구 API 사용하기</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Native_manifests">상호작용 명세 만들기</a></li> + <li><a href="/ko-KR/Add-ons/WebExtensions/User_actions">사용자와 상호작용하기</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/onboarding_upboarding_offboarding_best_practices">확장기능의 생애주기</a></li> +</ul> + +<h2 id="사용자_인터페이스">사용자 인터페이스</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface">개괄</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_action">도구모음 버튼</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups">도구모음 버튼과 팝업</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Page_actions">주소창 버튼</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups">주소창 버튼과 팝업</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items">상세 메뉴 항목</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars">사이드바</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages">설정 페이지</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages">확장기능 페이지</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications">알림</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox">주소창 자동추천</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels">개발자 도구 패널</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles">브라우저 스타일</a></li> +</ul> + +<h2 id="기능_구현">기능 구현</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests">HTTP 요청 가로채기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Modify_a_web_page">웹 페이지 수정하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar">도구모음에 버튼 추가하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page">설정 페이지 구성하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard">클립보드와 상호작용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_the_Tabs_API">Tabs API 사용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Bookmarks_API">Bookmarks API 사용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API">Cookies API 사용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_contextual_identities">contextual identities 사용하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page">외부 요소 삽입하기</a></li> +</ul> + +<ul> +</ul> + +<h2 id="다른_브라우저에서_옮겨오기">다른 브라우저에서 옮겨오기</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Firefox_differentiators">파이어폭스의 특성</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Porting_from_Google_Chrome">구글 크롬의 확장기능 가져오기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on">오래된 파이어폭스 확장기능 변환하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Developing_WebExtensions_for_Firefox_for_Android">안드로이드용 파이어폭스로 개발하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Developing_WebExtensions_for_Firefox_for_Android">썬더볼트로 개발하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Embedded_WebExtensions">섭입된 확장기능</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_the_Add-on_SDK">Add-on SDK와의 비교</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Comparison_with_XUL_XPCOM_extensions">XUL/XPCOM 확장기능과의 비교</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities">크롬과의 차이점</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Differences_between_desktop_and_Android">안드로이드와 PC의 차이점</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Differences_between_desktop_and_Android">API 구현의 차이점</a></li> +</ul> + +<h2 id="파이어폭스_생애주기">파이어폭스 생애주기</h2> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/User_experience_best_practices">사용자 경험</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">설치</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Debugging">디버깅</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Testing_persistent_and_restart_features">지속적인 테스트와 특성</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext">web-ext 와 작업하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/web-ext_command_reference">web-ext 명령어 일람</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID">확장기능과 애드온 ID</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Distribution_options">배포 옵션</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Request_the_right_permissions">올바른 권한 요청</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Sharing_objects_with_page_scripts">페이지 스크립트와 개체 공유하기</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Retiring_your_extension">확장기능 폐기하기</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Tips">팁과 트릭</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Development_Tools">확장기능 개발 도구</a></li> +</ul> +</div> + +<div class="section"> +<h2 id="Reference">Reference</h2> + +<h3 id="JavaScript_APIs">JavaScript APIs</h3> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API">JavaScript API 일람</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs">JavaScript API 브라우저 호환성</a></li> +</ul> + +<div class="twocolumns">{{ ListSubpages ("/en-US/Add-ons/WebExtensions/API") }}</div> + +<h3 id="Manifest_keys">Manifest keys</h3> + +<ul> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json">manifest.json 일람</a></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_compatibility_for_manifest.json">manifest.json 브라우저 호환성</a></li> +</ul> + +<div class="twocolumns">{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}</div> +</div> +</div> diff --git a/files/ko/mozilla/add-ons/webextensions/manifest.json/content_scripts/index.html b/files/ko/mozilla/add-ons/webextensions/manifest.json/content_scripts/index.html new file mode 100644 index 0000000000..b4d9b06443 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/manifest.json/content_scripts/index.html @@ -0,0 +1,227 @@ +--- +title: content_scripts +slug: Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts +--- +<div>{{AddonSidebar}}</div> + +<table class="fullwidth-table standard-table"> + <tbody> + <tr> + <th scope="row" style="width: 30%;">Type</th> + <td><code>Array</code></td> + </tr> + <tr> + <th scope="row">Mandatory</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Example</th> + <td> + <pre class="brush: json no-line-numbers"> +"content_scripts": [ + { + "matches": ["*://*.mozilla.org/*"], + "js": ["borderify.js"] + } +]</pre> + </td> + </tr> + </tbody> +</table> + +<p>Instructs the browser to load <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts">content scripts</a> into web pages whose URL matches a given pattern.</p> + +<p>This key is an array. Each item is an object which:</p> + +<ul> + <li><strong>must</strong> contain a key named <strong><code>matches</code></strong>, that specifies the URL patterns to be matched in order for the scripts to be loaded</li> + <li><strong>may</strong> contain keys named <strong><code>js</code></strong> and <strong><code>css</code></strong>, which list scripts to be loaded into matching pages</li> + <li><strong>may</strong> contain a number of other properties that control finer aspects of how and when content scripts are loaded</li> +</ul> + +<p>Details of all the keys you can include are given in the table below.</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Name</th> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><a id="all_frames" name="all_frames" style=""><code>all_frames</code></a></td> + <td><code>Boolean</code></td> + <td> + <p><code>true</code>: inject the scripts specified in <code><a href="#js">js</a></code> and <code><a href="#css">css</a></code> into all frames matching the specified URL requirements, even if the frame is not the topmost frame in a tab. This does not inject into child frames where only their parent matches the URL requirements and the child frame does not match the URL requirements. The URL requirements are checked for each frame independently.</p> + + <p><code>false</code>: inject only into frames matching the URL requirements which are the topmost frame in a tab.</p> + + <p>Defaults to <code>false</code>.</p> + </td> + </tr> + <tr> + <td><a id="css" name="css" style=""><code>css</code></a></td> + <td><code>Array</code></td> + <td> + <p>An array of paths, relative to manifest.json, referencing CSS files that will be injected into matching pages.</p> + + <p>Files are injected in the order given, and before the DOM is loaded.</p> + + <div class="blockIndicator note"> + <p>Firefox resolves URLs in injected CSS files relative to the CSS file itself, rather than to the page it's injected into.</p> + </div> + </td> + </tr> + <tr> + <td><a id="exclude_globs" name="exclude_globs" style=""><code>exclude_globs</code></a></td> + <td><code>Array</code></td> + <td>An array of strings containing wildcards. See <a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#Matching_URL_patterns">Matching URL patterns</a> below.</td> + </tr> + <tr> + <td><a id="exclude_matches" name="exclude_matches" style=""><code>exclude_matches</code></a></td> + <td><code>Array</code></td> + <td>An array of <a href="/en-US/Add-ons/WebExtensions/match_patterns">match patterns</a>. See <a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#Matching_URL_patterns">Matching URL patterns</a> below.</td> + </tr> + <tr> + <td><a id="include_globs" name="include_globs" style=""><code>include_globs</code></a></td> + <td><code>Array</code></td> + <td>An array of strings containing wildcards. See <a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#Matching_URL_patterns">Matching URL patterns</a> below.</td> + </tr> + <tr> + <td><a id="js" name="js" style=""><code>js</code></a></td> + <td><code>Array</code></td> + <td> + <p>An array of paths, relative to the manifest.json file, referencing JavaScript files that will be injected into matching pages.</p> + + <p>Files are injected in the order given. This means that, for example, if you include jQuery here followed by another content script, like this:</p> + + <pre class="brush: json no-line-numbers"> +<code>"js": ["jquery.js", "my-content-script.js"]</code></pre> + + <p>then <code>"my-content-script.js"</code> can use jQuery.</p> + + <p>Files are injected at the time specified by <code><a href="#run_at">run_at</a></code>.</p> + </td> + </tr> + <tr> + <td><code><a id="match_about_blank" name="match_about_blank" style="">match_about_blank</a></code></td> + <td><code>Boolean</code></td> + <td> + <p>Insert the content scripts into pages whose URL is "about:blank" or "about:srcdoc", if the URL of the page that opened or created this page <a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#Matching_URL_patterns">matches the patterns</a> specified in the rest of the <code>content_scripts</code> key.</p> + + <p>This is especially useful to run scripts in empty iframes , whose URL is "about:blank". To do this you should also set the <code>all_frames</code> key.</p> + + <p>For example, suppose you have a <code>content_scripts</code> key like this:</p> + + <pre class="brush: json no-line-numbers"> + "content_scripts": [ + { + "js": ["my-script.js"], + "matches": ["https://example.org/"], + "match_about_blank": true, + "all_frames": true + } + ]</pre> + + <p>If the user loads https://example.org/, and this page embeds an empty iframe, then "my-script.js" will be loaded into the iframe.</p> + + <p><code>match_about_blank</code> is supported in Firefox from version 52. Note that in Firefox, content scripts won't be injected into empty iframes at <code>"document_start"</code> even if you specify that value in <code><a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#run_at">run_at</a></code>.</p> + </td> + </tr> + <tr> + <td><a id="matches" name="matches" style=""><code>matches</code></a></td> + <td><code>Array</code></td> + <td> + <p>An array of <a href="/en-US/Add-ons/WebExtensions/match_patterns">match patterns</a>. See <a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts#Matching_URL_patterns">Matching URL patterns</a> below.</p> + + <p>This is the only mandatory key.</p> + </td> + </tr> + <tr> + <td><a id="run_at" name="run_at" style=""><code>run_at</code></a></td> + <td><code>String</code></td> + <td> + <p>This option determines when the scripts specified in <code><a href="#js">js</a></code> are injected. You can supply one of three strings here, each of which identifies a state in the process of loading a document. The states directly correspond to {{domxref("Document/readyState", "Document.readyState")}}:</p> + + <ul> + <li>"<code>document_start</code>": corresponds to <code>loading</code>. The DOM is still loading.</li> + <li>"<code>document_end</code>": corresponds to <code>interactive</code>. The DOM has finished loading, but resources such as scripts and images may still be loading.</li> + <li>"<code>document_idle</code>": corresponds to <code>complete</code>. The document and all its resources have finished loading.</li> + </ul> + + <p>The default value is <code>"document_idle"</code>.</p> + + <p>In all cases, files in <code><a href="#js">js</a></code> are injected after files in <code><a href="#css">css</a></code>.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Matching_URL_patterns">Matching URL patterns</h2> + +<p>The <code>"content_scripts"</code> key attaches content scripts to documents based on URL matching: if the document's URL matches the specification in the key, then the script will be attached. There are four properties inside <code>"content_scripts"</code> that you can use for this specification:</p> + +<ul> + <li><code>matches</code>: an array of <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match patterns</a>.</li> + <li><code>exclude_matches:</code> an array of <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns">match patterns</a>.</li> + <li><code>include_globs</code>: an array of <a href="#globs">globs</a>.</li> + <li><code>exclude_globs:</code> an array of <a href="#globs">globs</a>.</li> +</ul> + +<p>To match one of these properties, a URL must match at least one of the items in its array. For example, given a property like:</p> + +<pre class="brush: json no-line-numbers">"matches": ["*://*.example.org/*", "*://*.example.com/*"]</pre> + +<p>Both "http://example.org/" and "http://example.com/" will match.</p> + +<p>Since <code>matches</code> is the only mandatory key, the other three keys are used to limit further the URLs that match. To match the key as a whole, a URL must:</p> + +<ol> + <li>match the <code>matches</code> property</li> + <li>AND match the <code>include_globs</code> property, if present</li> + <li>AND NOT match the <code>exclude_matches</code> property, if present</li> + <li>AND NOT match the <code>exclude_globs</code> property, if present</li> +</ol> + +<h3 id="globs">globs</h3> + +<p>A glob is just a string that may contain wildcards. There are two types of wildcard, and you can combine them in the same glob:</p> + +<ul> + <li>"*" matches zero or more characters</li> + <li>"?" matches exactly one character.</li> +</ul> + +<p>For example: <code>"*na?i"</code> would match <code>"illuminati"</code> and <code>"annunaki"</code>, but not <code>"sagnarelli"</code>.</p> + +<h2 id="Example">Example</h2> + +<pre class="brush: json no-line-numbers">"content_scripts": [ + { + "matches": ["*://*.mozilla.org/*"], + "js": ["borderify.js"] + } +]</pre> + +<p>This injects a single content script "borderify.js" into all pages under "mozilla.org" or any of its subdomains, whether served over HTTP or HTTPS.</p> + +<pre class="brush: json no-line-numbers"> "content_scripts": [ + { + "exclude_matches": ["*://developer.mozilla.org/*"], + "matches": ["*://*.mozilla.org/*"], + "js": ["jquery.js", "borderify.js"] + } + ]</pre> + +<p>This injects two content scripts into all pages under "mozilla.org" or any of its subdomains except "developer.mozilla.org", whether served over HTTP or HTTPS.</p> + +<p>The content scripts see the same view of the DOM and are injected in the order they appear in the array, so "borderify.js" can see global variables added by "jquery.js".</p> + +<h2 id="Browser_compatibility">Browser compatibility</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.manifest.content_scripts")}}</p> diff --git a/files/ko/mozilla/add-ons/webextensions/manifest.json/index.html b/files/ko/mozilla/add-ons/webextensions/manifest.json/index.html new file mode 100644 index 0000000000..3d4776f047 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/manifest.json/index.html @@ -0,0 +1,101 @@ +--- +title: manifest.json +slug: Mozilla/Add-ons/WebExtensions/manifest.json +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json +--- +<p>{{AddonSidebar}}</p> + +<p>manifest.json 파일은 json 포맷 파일로서, 모든 웹 익스텐션이 포함하고 있어야 하는 파일입니다. </p> + +<p>manifest.json을 사용함으로써, 당신은 당신의 익스텐션의 이름, 버젼과 같은 기본 정보를 명시하며, 또한 당신의 익스텐션의 기능, 예를 들어 기본 스크립트, 내용 스크립트, 브라우져 활동 등과 같은 측면을 명시합니다. </p> + +<p>manifest.json에 지원되는 키들은 아래와 같습니다.</p> + +<p>{{ ListSubpages ("/en-US/Add-ons/WebExtensions/manifest.json") }}</p> + +<div class="twocolumns"> </div> + +<p><code>"manifest_version"</code>, <code>"version"</code>, <code>"name" 키들은 반드시 있어야 합니다. </code></p> + +<p>"_locales" 경로가 있다면, <code>"default_locale"은 반드시 있어야 하며, </code>"_locales" 경로가 없다면, <code>"default_locale"은 없어야 합니다. </code></p> + +<p><code>"applications"는 구글 크롬에서는 지원되지 않고, 파이어폭스 48 이전 버젼에는 의무적으로 있어야 합니다. </code></p> + +<p>간단한 manifest.json 구문은 다음과 같습니다:</p> + +<pre class="brush: json">{ + + "applications": { + "gecko": { + "id": "addon@example.com", + "strict_min_version": "42.0", + "strict_max_version": "50.*", + "update_url": "https://example.com/updates.json" + } + }, + + "background": { + "scripts": ["jquery.js", "my-background.js"], + "page": "my-background.html" + }, + + "browser_action": { + "default_icon": { + "19": "button/geo-19.png", + "38": "button/geo-38.png" + }, + "default_title": "Whereami?", + "default_popup": "popup/geo.html" + }, + + "commands": { + "toggle-feature": { + "suggested_key": { + "default": "Ctrl+Shift+Y", + "linux": "Ctrl+Shift+U" + }, + "description": "Send a 'toggle-feature' event" + } + }, + + "content_security_policy": "script-src 'self' https://example.com; object-src 'self'", + + "content_scripts": [ + { + "exclude_matches": ["*://developer.mozilla.org/*"], + "matches": ["*://*.mozilla.org/*"], + "js": ["borderify.js"] + } + ], + + "default_locale": "en", + + "description": "...", + + "icons": { + "48": "icon.png", + "96": "icon@2x.png" + }, + + "manifest_version": 2, + + "name": "...", + + "page_action": { + "default_icon": { + "19": "button/geo-19.png", + "38": "button/geo-38.png" + }, + "default_title": "Whereami?", + "default_popup": "popup/geo.html" + }, + + "permissions": ["webNavigation"], + + "version": "0.1", + + "web_accessible_resources": ["images/my-image.png"] + +}</pre> + +<p> </p> diff --git a/files/ko/mozilla/add-ons/webextensions/manifest.json/page_action/index.html b/files/ko/mozilla/add-ons/webextensions/manifest.json/page_action/index.html new file mode 100644 index 0000000000..9a4b85ea74 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/manifest.json/page_action/index.html @@ -0,0 +1,200 @@ +--- +title: page_action +slug: Mozilla/Add-ons/WebExtensions/manifest.json/page_action +tags: + - 애드온 + - 웹확장 + - 확장 +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/page_action +--- +<div>{{AddonSidebar}}</div> + +<table class="fullwidth-table standard-table"> + <tbody> + <tr> + <th scope="row" style="width: 30%;">Type</th> + <td><code>Object</code></td> + </tr> + <tr> + <th scope="row">Mandatory</th> + <td>No</td> + </tr> + <tr> + <th scope="row">Example</th> + <td> + <pre class="brush: json no-line-numbers"> +"page_action": { + "browser_style": true, + "default_icon": { + "19": "button/geo-19.png", + "38": "button/geo-38.png" + }, + "default_title": "Whereami?", + "default_popup": "popup/geo.html" +}</pre> + </td> + </tr> + </tbody> +</table> + +<p>페이지 액션은 브라우저의 URL 바 안에 추가되는 아이콘이다.</p> + +<p>필요하면 HTML, CSS, 그리고 자바스크립트를 사용하는 팝업을 띄울 수 있다.</p> + +<p>팝업이 있으면, 아이콘을 클릭할 때 팝업이 열리고, 팝업 안의 자바스크립트가 사용자와의 상호작업을 처리할 수 있다. 팝업이 없으면, 아이콘을 클릭할 때 확장의 <a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_pages">background 스크립트</a>에 click 이벤트가 전달된다.</p> + +<p><a href="/en-US/Add-ons/WebExtensions/API/pageAction">pageAction API</a>을 사용하면 프로그램적으로 페이지 액션을 만들고 관리할 수 있다.</p> + +<p>페이지 액션은 브라우저 액션과 비슷하다. 단지 브라우저 전체가 아니라 특정 웹페이지와만 연관된다는 점이 다르다. 액션의 대상 페이지가 분명하다면 그 페이지에서만 표시되는 페이지 액션을 사용해야 한다. 액션이 모든 페이지를 대상으로 하거나 브라우저 그 자체가 대상이라면 브라우저 액션을 사용하라.</p> + +<p>브라우저 액션은 기본이 표시되는 것이지만 페이지 액션은 기본적으로 숨겨진다. 탭에 <code><a href="/en-US/Add-ons/WebExtensions/API/pageAction/show">pageAction.show()</a></code>를 호출하거나, <code>show_matches</code> 속성을 줘야 표시할 수 있다.</p> + +<h2 id="문법">문법</h2> + +<p><code>page_action</code>은 세 가지 속성들 중에 몇 가지를 가지는 객체다(역주: 파이어폭스 외의 브라우저에서도 지원되는 속성은 세가지 뿐이다). 모두 선택사항이다:</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Name</th> + <th scope="col">Type</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles">browser_style</a></code></td> + <td><code>Boolean</code></td> + <td> + <p>선택, 기본값은 <code>false</code>.</p> + + <p>사용하면, 팝업과 브라우저의 UI와 <code>browser_style</code>을 사용하는 다른 확장의 모습이 일관되게 보이게 하는 스타일시트를 포함한다. 기본값은 <code>false</code>지만 팝업이 브라우저의 다른 UI와 일관되게 하려면, 스타일시트가 포함될 수 있도록 <code>true</code>로 하는 것이 권장한다.</p> + + <p>파이어폭스에서, 이 스타일시트는 chrome://browser/content/extension.css에서 볼 수 있다. OS X에서는 chrome://browser/content/extension-mac.css다.</p> + + <p><a href="https://firefoxux.github.io/StyleGuide/#/controls">파이어폭스 스타일 가이드</a>는 팝업의 요소가 특정 스타일을 갖게하는 클래스들에 대해 설명한다.</p> + + <p><a href="https://github.com/mdn/webextensions-examples/tree/master/latest-download">최종-다운로드</a> 예제 확장 프로그램은 팝업에 <code>browser_style</code>을 사용한다.</p> + </td> + </tr> + <tr> + <td><code>default_icon</code></td> + <td><code>Object</code> or <code>String</code></td> + <td> + <p>액션이 사용하는 아이콘.</p> + + <p>권장은 19x19 픽셀과 38x38 픽셀 두 종류가 제공되는 것이다. 아래처럼 각각 "19" 와 "38"이라는 속성 이름을 사용한다:</p> + + <pre class="brush: json no-line-numbers"> + "default_icon": { + "19": "geo-19.png", + "38": "geo-38.png" + }</pre> + + <p>이렇게 하면 화면 해상도에 따라 적절한 크기를 사용하게 된다.</p> + + <p>아래처럼 하나의 문자열로 할 수도 있다:</p> + + <pre class="brush: json no-line-numbers"> +"default_icon": "geo.png"</pre> + + <p>이렇게 하면 툴바에 맞게 크기가 조정될 것이다. 흐릿해질 수 있다.</p> + </td> + </tr> + <tr> + <td><code>default_popup</code></td> + <td><code>String</code></td> + <td> + <p>팝업으로 띄울 HTML 파일의 경로.</p> + + <p>HTML 파일은 일반 웹 페이지처럼 <code><a href="/en-US/docs/Web/HTML/Element/link"><link></a></code>와 <code><a href="/en-US/docs/Web/HTML/Element/script"><script></a></code> 요소를 사용해서 CSS와 자바스크립트를 포함할 수 있다. 하지만 <code><a href="/en-US/docs/Web/HTML/Element/script"><script></a></code> 사이에 코드를 직접 포함하면 Content Violation Policy 에러가 발생하므로, <code><a href="/en-US/docs/Web/HTML/Element/script">src</a></code> 속성으로 분리된 스크립트 파일을 올려야 한다.</p> + + <p>보통의 웹페이지와 달리, 팝업에서 실행되는 자바스크립트는 모든 <a href="/en-US/Add-ons/WebExtensions/API">WebExtension API</a>를 사용할 수 있다(당연히 필요한 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">권한</a>을 가져야 한다).</p> + + <p>이것은 <a href="/en-US/Add-ons/WebExtensions/Internationalization#Internationalizing_manifest.json">지역화 가능 속성</a>이다.</p> + </td> + </tr> + <tr> + <td><code>default_title</code></td> + <td><code>String</code></td> + <td> + <p>아이콘에 마우스가 올려지면 표시되는 툴팁.</p> + + <p>이것은 <a href="/en-US/Add-ons/WebExtensions/Internationalization#Internationalizing_manifest.json">지역화 가능 속성</a>이다.</p> + </td> + </tr> + <tr> + <td><code>hide_matches</code></td> + <td><code>Array</code> of <code>Match Pattern</code> except <code><all_urls></code></td> + <td> + <p>주어진 <a href="/en-US/Add-ons/WebExtensions/match_patterns">선별식</a>에 맞는 URL에 대해 페이지 액션을 숨긴다.</p> + + <p>하지만 페이지 액션은 기본적으로 숨겨지고 <code>show_matches</code>와 맞아야만 보이기 때문에, <code>반드시 show_matches</code>가 있어야 의미가 있다. 이 값은 <code>show_matches</code> 일부를 제외하는 역할을 한다. 예를 들어 값이 다음과 같다면:</p> + + <pre class="brush: json"> +"page_action": { + "show_matches": ["https://*.mozilla.org/*"], + "hide_matches": ["https://developer.mozilla.org/*"] +}</pre> + + <p>기본은 "mozilla.org"인 모든 HTTPS URL에 대해 페이지 액션이 표시되는 것이지만, "developer.mozilla.org"인 경우는 제외라 표시되지 않는다.</p> + </td> + </tr> + <tr> + <td><code>show_matches</code></td> + <td><code>Array</code> of <code>Match Pattern</code></td> + <td> + <p>주어진 패턴에 일치하는 URL에 대해 페이지 액션을 보인다.</p> + + <p><code>hide_matches</code>도 보기.</p> + </td> + </tr> + <tr> + <td><code>pinned</code></td> + <td><code>Boolean</code></td> + <td> + <p>선택, 기본값은 <code>true</code>.</p> + + <p>주소창에 페이지 액션이 기본적으로 나타나는지를 결정한다.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<pre class="brush: json no-line-numbers">"page_action": { + "default_icon": { + "19": "button/geo-19.png", + "38": "button/geo-38.png" + } +}</pre> + +<p>그냥 아이콘만 있는 페이지 액션으로 아이콘을 누르면 확장의 background 스크립트는 아래처럼 해서 click 이벤트를 받을 수 있다:</p> + +<pre class="brush: js no-line-numbers"> browser.pageAction.onClicked.addListener(handleClick);</pre> + +<pre class="brush: json no-line-numbers">"page_action": { + "default_icon": { + "19": "button/geo-19.png", + "38": "button/geo-38.png" + }, + "default_title": "Whereami?", + "default_popup": "popup/geo.html" +}</pre> + +<p>아이콘, 제목, 팝업이 있는 페이지 액션으로 아이콘을 누르면 팝업이 보일 것이다.</p> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("webextensions.manifest.page_action")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></code></li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action">sidebar_action</a></code></li> + <li><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles">Browser styles</a></li> +</ul> diff --git a/files/ko/mozilla/add-ons/webextensions/prerequisites/index.html b/files/ko/mozilla/add-ons/webextensions/prerequisites/index.html new file mode 100644 index 0000000000..ffe3aaf677 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/prerequisites/index.html @@ -0,0 +1,10 @@ +--- +title: Prerequisites +slug: Mozilla/Add-ons/WebExtensions/Prerequisites +translation_of: Mozilla/Add-ons/WebExtensions/Prerequisites +--- +<div>{{AddonSidebar}}</div> + +<div>파이어폭스 45 이후 버젼만 있으면 됩니다. </div> + +<div>시작하려면 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension">Your first WebExtension</a> 을 보세요. </div> diff --git a/files/ko/mozilla/add-ons/webextensions/user_actions/index.html b/files/ko/mozilla/add-ons/webextensions/user_actions/index.html new file mode 100644 index 0000000000..84a7210eef --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/user_actions/index.html @@ -0,0 +1,43 @@ +--- +title: 사용자 행동 +slug: Mozilla/Add-ons/WebExtensions/User_actions +translation_of: Mozilla/Add-ons/WebExtensions/User_actions +--- +<div>{{AddonSidebar}}</div> + +<p>Some WebExtension APIs perform functions that are generally performed as a result of a user action. For example:</p> + +<ul> + <li>a browser action with a popup will display the popup when the user clicks it, but there's also a {{WebExtAPIRef("browserAction.openPopup")}} API enabling an extension to open the popup programmatically.</li> + <li>if an extension adds a sidebar, it is typically opened by the user via some part of the browser's built-in user interface, such as the View/Sidebar menu. But there's also a {{WebExtAPIRef("sidebarAction.open")}} API enabling an extension to open their sidebar programmatically.</li> +</ul> + +<p>To follow the principle of "no surprises", APIs like this can only be called from inside the handler for a user action. User actions include the following:</p> + +<ul> + <li>Clicking the extension's browser action or page action.</li> + <li>Selecting a context menu item defined by the extension.</li> + <li>Activating a keyboard shortcut defined by the extension (this only treated as a user action from Firefox 63 onwards).</li> + <li>Clicking a button in a page bundled with the extension.</li> +</ul> + +<p>For example:</p> + +<pre class="brush: js">function handleClick() { + browser.sidebarAction.open(); +} + +browser.browserAction.onClicked.addListener(handleClick);</pre> + +<p>Note that user actions in normal web pages are not treated as user actions for this purpose. For example, if a user clicks a button in a normal web page, and a content script has added a click handler for that button and in that handler sends a message to the extension's background page, then the background page message handler is not considered to be handling a user action.</p> + +<p>Also, if a user input handler waits on a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>, then its status as a user input handler is lost. For example:</p> + +<pre class="brush: js">async function handleClick() { + let result = await someAsyncFunction(); + + // this will fail, because the handler lost its "user action handler" status + browser.sidebarAction.open(); +} + +browser.browserAction.onClicked.addListener(handleClick);</pre> diff --git a/files/ko/mozilla/add-ons/webextensions/user_interface/index.html b/files/ko/mozilla/add-ons/webextensions/user_interface/index.html new file mode 100644 index 0000000000..e9041bc4dc --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/user_interface/index.html @@ -0,0 +1,96 @@ +--- +title: User interface +slug: Mozilla/Add-ons/WebExtensions/user_interface +tags: + - Landing + - NeedsTranslation + - TopicStub + - User Interface + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/user_interface +--- +<div>{{AddonSidebar}}</div> + +<p>Extensions that use WebExtension APIs are provided with several user interface options so that their functionality can be made available to the user. A summary of those options is provided below, with a more detailed introduction to each user interface option in this section.</p> + +<div class="note"> +<p>For advice on using these UI components to create a great user experience in your extension, please see the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/User_experience_best_practices">User experience best practices</a> article.</p> +</div> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">UI option</th> + <th scope="col">Description</th> + <th scope="col" style="width: 350px;">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/Add-ons/WebExtensions/user_interface/Browser_action">Toolbar button</a> (browser action)</td> + <td>A button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.</td> + <td><img alt="Example showing a toolbar button (browser action)." src="https://mdn.mozillademos.org/files/15751/browser-action.png" style="height: 364px; width: 700px;"></td> + </tr> + <tr> + <td>Toolbar button with a <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups">popup</a></td> + <td>A popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.</td> + <td><img alt="Example of the pop-up on a toolbar button" src="https://mdn.mozillademos.org/files/15753/popup-shadow.png" style="height: 624px; width: 700px;"></td> + </tr> + <tr> + <td><a href="/Add-ons/WebExtensions/user_interface/Page_actions">Address bar button</a> (page action)</td> + <td>A button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.</td> + <td><img alt="Example showing an address bar button (page action) " src="https://mdn.mozillademos.org/files/15745/address_bar_button.png" style="height: 348px; width: 700px;"></td> + </tr> + <tr> + <td>Address bar button with a <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Popups">popup</a></td> + <td>A popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.</td> + <td><img alt="Example of a popup on the address bar button" src="https://mdn.mozillademos.org/files/15747/page_action_popup.png" style="height: 524px; width: 700px;"></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items">Context menu item</a></td> + <td>Menu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.</td> + <td><img alt="Example of content menu items added by a WebExtension, from the context-menu-demo example" src="https://mdn.mozillademos.org/files/15756/context_menu_example.png" style="height: 942px; width: 864px;"></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Sidebars">Sidebar</a></td> + <td> + <p dir="ltr">An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.</p> + </td> + <td><img alt="Example of a sidebar" src="https://mdn.mozillademos.org/files/15755/bookmarks-sidebar.png" style="height: 846px; width: 700px;"></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Options_pages">Options page</a></td> + <td>A page that enables you to define preferences for your extension that your users can change. The user can access this page from the browser's add-ons manager.</td> + <td><img alt="Example showing the options page content added in the favorite colors example." src="https://mdn.mozillademos.org/files/15748/options_page.png"></td> + </tr> + <tr> + <td><a href="/Add-ons/WebExtensions/user_interface/Extension_pages">Extension page</a></td> + <td>Use web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.</td> + <td><img alt="Example of a simple bundled page displayed as a detached panel." src="https://mdn.mozillademos.org/files/15752/bundled_page_as_panel_small.png" style="height: 432px; width: 700px;"></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Notifications">Notification</a></td> + <td>Transient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).</td> + <td><img alt="Example of an extension triggered system notification" src="https://mdn.mozillademos.org/files/15754/notify-shadowed.png" style="height: 294px; width: 780px;"></td> + </tr> + <tr> + <td><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/Omnibox">Address bar suggestion</a></td> + <td>Offer custom address bar suggestions when the user enters a keyword.</td> + <td><img alt="Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions." src="https://mdn.mozillademos.org/files/15749/omnibox_example_small.png" style="height: 464px; width: 700px;"></td> + </tr> + <tr> + <td><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels">Developer tools panel</a></td> + <td>A tab with an associated HTML document that displays in the browser's developer tools.</td> + <td><img alt="Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions." src="https://mdn.mozillademos.org/files/15746/developer_panel_tab.png" style="height: 224px; width: 700px;"></td> + </tr> + </tbody> +</table> + +<p>The following how-to guides provide step-by-step guidance to creating some of these user interface options:</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Add_a_button_to_the_toolbar">Add a button to the toolbar</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Implement_a_settings_page">Implement a settings page</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools">Extending the developer tools</a></li> + <li><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/user_interface/Browser_styles">Browser styles</a></li> +</ul> diff --git a/files/ko/mozilla/add-ons/webextensions/user_interface/page_actions/index.html b/files/ko/mozilla/add-ons/webextensions/user_interface/page_actions/index.html new file mode 100644 index 0000000000..568d5feb97 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/user_interface/page_actions/index.html @@ -0,0 +1,98 @@ +--- +title: Address bar button +slug: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions +tags: + - 사용자 인터페이스 + - 웹확장 +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions +--- +<div>{{AddonSidebar}}</div> + +<p>주소줄에 추가되는 버튼으로 사용자가 확장 프로그램과 상호작용하는 일명 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction">페이지 </a><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction">액션</a>을 말한다.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/15745/address_bar_button.png" style="display: block; height: 174px; margin-left: auto; margin-right: auto; width: 350px;"></p> + +<h2 id="페이지_액션과_브라우저_액션">페이지 액션과 브라우저 액션</h2> + +<p>주소줄 버튼(또는 페이지 액션)은 툴바 버튼(또는 브라우저 액션)과 아주 비슷하다.</p> + +<p>차이점은:</p> + +<ul> + <li>위치: + <ul> + <li>페이지 액션은 브라우저의 주소줄에 표시된다.</li> + <li>브라우저 액션은 주소줄 밖 브라우저의 툴바에 표시된다.</li> + </ul> + </li> + <li>보임: + <ul> + <li>페이지 액션은 평소에는 보통 숨겨지고(show_matches와 hide_matches <a href="/en-US/Add-ons/WebExtensions/manifest.json/page_action">매니페스트 항목</a>으로 바꿀 수 있다), 해당 탭에 보이거나 숨길 때는 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/PageAction/show" title="Shows the page action for a given tab. The page action is shown whenever the given tab is the active tab."><code>pageAction.show()</code></a>와 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/PageAction/hide" title="Hides the page action for a given tab."><code>pageAction.hide()</code></a> 를 호출한다.</li> + <li>브라우저 액션은 항상 보인다.</li> + </ul> + </li> +</ul> + +<p>하고자 하는 동작이 현재 페이지에 대한 것이면 페이지 액션을 사용하고, 전체 또는 여러 페이지가 대상이라면 브라우저 액션을 사용한다. 예를 들어:</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="row">유형</th> + <th scope="col">Bookmarks action</th> + <th scope="col">Content action</th> + <th scope="col">Tabs operation</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">페이지 액션</th> + <td>Bookmark this page</td> + <td>Reddit enhancement</td> + <td>Send tab</td> + </tr> + <tr> + <th scope="row">브라우저 액션</th> + <td>Show all bookmarks</td> + <td>Enable ad-blocking</td> + <td>Sync all open tabs</td> + </tr> + </tbody> +</table> + +<p> </p> + +<h2 id="페이지_액션_기술하기">페이지 액션 기술하기</h2> + +<p> </p> + +<p>페이지 액션의 속성은 manifest.json의 <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action">page_action</a></code> 항목에서 정의한다:</p> + +<pre class="brush: json line-numbers language-json"><code class="language-json"><span class="key token">"page_action":</span> <span class="punctuation token">{</span> + <span class="key token">"browser_style":</span> <span class="keyword token">true</span><span class="punctuation token">,</span> + <span class="key token">"default_icon":</span> <span class="punctuation token">{</span> + <span class="key token">"19":</span> <span class="string token">"button/geo-19.png"</span><span class="punctuation token">,</span> + <span class="key token">"38":</span> <span class="string token">"button/geo-38.png"</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="key token">"default_title":</span> <span class="string token">"Whereami?"</span> +<span class="punctuation token">}</span></code></pre> + +<p>꼭 있어야 하는 항목은 <code>default_icon</code>이다.</p> + +<p>페이지 액션을 기술하는 길은 두 가지다: <a href="/en-US/Add-ons/WebExtensions/Popups">팝업</a>이 있는가. 없는가. 팝업이 없으면, 사용자 클릭은 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction/onClicked" title="Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup."><code>pageAction.onClicked</code></a>을 청취하는 확장 프로그램에 이벤트를 전달된다:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">browser<span class="punctuation token">.</span>pageAction<span class="punctuation token">.</span>onClicked<span class="punctuation token">.</span><span class="function token">addListener</span><span class="punctuation token">(</span>handleClick<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>팝업이 있으면, 클릭 이벤트는 없다: 대신, 팝업창이 열린다. 사용자는 팝업으로 일을 하고, 팝업창 바깥을 클릭하면 자동으로 닫힌다. <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Popups">팝업</a> 글에 팝업을 만들고 관리하는 보다 자세한 내용이 있다.</p> + +<p>주목! 확장 프로그램은 페이지 액션을 하나만 가질 수 있다.</p> + +<p>페이지 액션의 속성은 <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/pageAction">pageAction</a></code> API로 프로그램적으로 바꿀 수 있다.</p> + +<h2 id="아이콘">아이콘</h2> + +<p>페이지 액션에서 어떻게 아이콘을 만들고 사용하는지에 대한 자세한 내용은 <a class="grey-90 no-underline hover-no-underline" href="https://design.firefox.com/photon/index.html">Photon Design System</a> 문서에서 <a href="https://design.firefox.com/photon/visuals/iconography.html">Iconography</a>을 보라.</p> + +<h2 id="예제">예제</h2> + +<p>GitHub <a href="https://github.com/mdn/webextensions-examples">webextensions-examples</a> 저장소에 팝업없는 페이지 액션 예제 <a href="https://github.com/mdn/webextensions-examples/tree/master/chill-out">chill-out</a>가 있다.</p> diff --git a/files/ko/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/ko/mozilla/add-ons/webextensions/what_are_webextensions/index.html new file mode 100644 index 0000000000..95d5af0f04 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/what_are_webextensions/index.html @@ -0,0 +1,28 @@ +--- +title: What are extensions? +slug: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +<div>{{AddonSidebar}}</div> + +<div>Extension(이하 확장앱)은 웹 브라우저의 기능을 수정하는 코드를 지칭합니다. 확장앱은 표준 웹 기술(JavaScript, HTML 그리고 CSS)과 일부 전용 JavaScript API를 사용하여 작성됩니다. 여러 가지 특징이 있지만 무엇보다도 확장앱은 브라우저에 새로운 기능을 추가할 수 있고 특정 웹사이트의 모양이나 내용을 변경할 수 있다는 점이 대표적입니다.</div> + +<div> </div> + +<div>Firefox 용 확장 프로그램은 확장앱 개발을 위한 크로스 브라우저 시스템인 WebExtensions API를 사용하여 만들어집니다. 대부분의 경우 API는 Google 크롬 및 Opera에서 지원하는 <a href="https://developer.chrome.com/extensions">extension API</a>와 호환됩니다. 대부분의 경우 이러한 브라우저 용으로 작성된 확장 프로그램은 Firefox 또는 Microsoft Edge에서 <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension">약간의 변경</a>만으로 실행됩니다. API는 <a href="https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox">멀티프로세스 Firefox</a>와도 완벽하게 호환됩니다.</div> + +<div> </div> + +<div>과거에는 <a href="https://developer.mozilla.org/en-US/Add-ons/Overlay_Extensions">XUL/XPCOM overlays</a>, <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/Bootstrapped_extensions">bootstrapped extensions</a>, 또는 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/SDK">Add-on SDK</a> 중 하나의 방법으로 Firefox Extension을 개발했습니다. 이제 2017년 11월을 마지막으로 WebExtensions API가 유일한 Firefox 확장앱 개발 방법으로 통합되고, 기존의 방법은 더 이상 사용되지 않을 예정입니다. </div> + +<div> </div> + +<div>질문 혹은 아이디어가 있거나, 기존 Extension을 WebExtensions API로 마이그레이션 할 때 도움이 필요하다면 <a class="external external-icon" href="https://mail.mozilla.org/listinfo/dev-addons">dev-addons 메일링 리스트</a>나 <a class="external external-icon" href="https://wiki.mozilla.org/IRC">IRC</a>의 <a href="irc://irc.mozilla.org/extdev">#extdev</a>로 요청해주세요.</div> + +<h2 id="Whats_next">What's next?</h2> + +<ul> + <li>확장앱 예시를 확인하려면 <a href="/ko/Add-ons/WebExtensions/Examples">Example extensions</a> 참조.</li> + <li>확장앱<span class="translation">의 구조에 대한 내용은 </span><a href="/ko/Add-ons/WebExtensions/Anatomy_of_a_WebExtension">Anatomy of an extension</a> 참조.</li> + <li>간단한 확장앱을 만들어보려면 <a href="/ko/Add-ons/WebExtensions/Your_first_WebExtension">Your first extension</a> 참조.</li> +</ul> diff --git a/files/ko/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/ko/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..e7de79a4d0 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,154 @@ +--- +title: Your first extension +slug: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +tags: + - WebExtensions + - 가이드 +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +<div>{{AddonSidebar}}</div> + +<p>이 글에서 우리는 "mozilla.org"와 그 하위 도메인 페이지에서 불러온 페이지에 붉은 테두리를 추가하는 확장 기능을 만들게 됩니다. 이를 통해 어떻게 Firefox를 위한 확장 기능을 만들 수 있는지 알아보고자 합니다.</p> + +<p>이 예제의 소스코드는 GitHub에서 받을 수 있습니다.<br> + <a href="https://github.com/mdn/webextensions-examples/tree/master/borderify">https://github.com/mdn/webextensions-examples/tree/master/borderify</a></p> + +<p>우선, 파이어폭스의 버전이 45 이상이여야 합니다.</p> + +<h2 id="확장기능_만들기">확장기능 만들기</h2> + +<p>새 디렉토리를 만들고 그 디렉토리 안으로 들어갑니다.</p> + +<pre class="brush: bash">mkdir borderify +cd borderify</pre> + +<h3 id="manifest.json">manifest.json</h3> + +<p>이제 "borderify" 폴더 안에 "manifest.json" 파일을 만들어야 합니다. 아래 내용을 작성해 주세요.</p> + +<pre class="brush: json line-numbers language-json"><code class="language-json"><span class="punctuation token">{</span> + + <span class="key token">"manifest_version":</span> <span class="number token">2</span><span class="punctuation token">,</span> + <span class="key token">"name":</span> <span class="string token">"Borderify"</span><span class="punctuation token">,</span> + <span class="key token">"version":</span> <span class="string token">"1.0"</span><span class="punctuation token">,</span> + + <span class="key token">"description":</span> <span class="string token">"Adds a red border to all webpages matching mozilla.org."</span><span class="punctuation token">,</span> + + <span class="key token">"icons":</span> <span class="punctuation token">{</span> + <span class="key token">"48":</span> <span class="string token">"icons/border-48.png"</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + + <span class="key token">"content_scripts":</span> <span class="punctuation token">[</span> + <span class="punctuation token">{</span> + <span class="key token">"matches":</span> <span class="punctuation token">[</span><span class="string token">"*://*.mozilla.org/*"</span><span class="punctuation token">]</span><span class="punctuation token">,</span> + <span class="key token">"js":</span> <span class="punctuation token">[</span><span class="string token">"borderify.js"</span><span class="punctuation token">]</span> + <span class="punctuation token">}</span> + <span class="punctuation token">]</span> + +<span class="punctuation token">}</span></code></pre> + +<ul> + <li><code><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/manifest_version">manifest_version</a></code>, <code><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/name">name</a></code>, <code><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/version">version</a></code>, 이 세가지 키는 반드시 필요합니다. 확장의 기본 메타 데이터를 담고 있습니다.</li> + <li><code><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/manifest.json/description">description</a></code>은 없어도 괜찮지만 포함하는 게 좋습니다. 확장 관리자 화면에서 볼 수 있습니다.</li> + <li><code><a href="/en-US/Add-ons/WebExtensions/manifest.json/icons">icons</a></code>은 없어도 괜찮지만 역시 포함하는 편이 좋습니다<span class="translation">. 이는 확장의 아이콘을 결정하며 확장 관리자 화면에서 볼 수 있습니다.</span></li> +</ul> + +<p>가장 재밌는 키는 <code><a href="/en-US/Add-ons/WebExtensions/manifest.json/content_scripts">content_scripts</a></code> 입니다. 이 키는 URL이 패턴과 일치하는 페이지에 스크립트를 주입하도록 Firefox에 요청하는 역할을 합니다. 이 예제의 경우, "mozilla.org"와 그 하위 도메인에서 제공되는 모든 HTTP와 HTTPS 페이지에 "borderify.js" 스크립트를 주입하도록 Firefox에 요청합니다.</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/Content_scripts">content scripts에 대해 더 알아보기</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Match_patterns">match patterns에 대해 더 알아보기</a></li> +</ul> + +<div class="warning"> +<p><a href="/en-US/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID#When_do_you_need_an_Add-on_ID">확장에 ID를 지정해야 할 수도 있습니다</a><span class="translation">. 애드온</span> ID를 지정해야 한다면, <code>manifest.json</code> 파일에 <code>application</code> 키를 작성한 다음 gecko.id 프로퍼티를 설정하면 됩니다.</p> + +<pre class="brush: json">"applications": { + "gecko": { + "id": "borderify@example.com" + } +}</pre> +</div> + +<h3 id="iconsborder-48.png">icons/border-48.png</h3> + +<p>확장기능에는 아이콘이 필요합니다. 이 아이콘은 확장 관리자의 목록에 나타납니다. 우리의 manifest.json은 "icons/border-48.png"를 아이콘으로 사용하겠다고 정했습니다.</p> + +<p>borderify 디렉토리 안에 icons 디렉토리를 만들고, "border-48.png"라는 이름으로 아이콘을 저장합니다. <a href="https://github.com/mdn/webextensions-examples/blob/master/borderify/icons/border-48.png">예제에 포함된 아이콘</a>이나, <a href="https://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-ShareAlike</a> 라이선스로 배포되는 Google Material Design 아이콘 세트에서 골라도 좋습니다.</p> + +<p>사용할 아이콘은 48픽셀 정사각형이여야 합니다. 원한다면 고해상도 디스플레이를 위해서 96x96 픽셀의 아이콘과 같이 제공할 수도 있습니다. 만약 그렇게 한다면 manifest.json의 icons 객체에 <code>96</code> 프로퍼티로 지정해줘야 합니다.</p> + +<pre class="brush: json">"icons": { + "48": "icons/border-48.png", + "96": "icons/border-96.png" +}</pre> + +<p>대신 SVG 파일을 사용할 수도 있습니다. 그러면 자동으로 딱 맞게 조절되어 적용됩니다. (만약 SVG에 텍스트가 포함되어 있다면 사용하는 툴에서 "패스로 변환하기" 기능을 사용해 텍스트를 패스로 변경해주세요. 그래야 원하는 위치와 크기로 확대/축소가 이뤄집니다.)</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/manifest.json/icons">아이콘을 지정하는 방법에 대해 더 알아보기</a></li> +</ul> + +<h3 id="borderify.js">borderify.js</h3> + +<p>마지막으로 borderify.js 파일을 borderify 디렉토리에 만들고 아래 내용으로 저장해주세요.</p> + +<pre class="brush: js">document.body.style.border = "5px solid red";</pre> + +<p>이 스크립트는 manifest.json의 <code>content_scripts</code>키로 주어진 패턴에 매칭 될 때 페이지에 삽입됩니다. 스크립트는 원래 페이지에 포함되어 있던 스크립트처럼, 문서 자체에 직접 접근할 수 있게 됩니다.</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/Content_scripts">content scripts에 대해 더 알아보기</a></li> +</ul> + +<h2 id="사용해보기">사용해보기</h2> + +<p>우선 파일들이 원하는 위치에 있는지 다시 확인 해보세요.</p> + +<pre>borderify/ + icons/ + border-48.png + borderify.js + manifest.json</pre> + +<h3 id="설치">설치</h3> + +<p>Firefox로 "about:debugging" 페이지에 들어갑니다. "임시 확장기능 로드"를 클릭해 확장기능 디렉토리를 선택합니다.</p> + +<p>{{EmbedYouTube("cer9EUKegG4")}}</p> + +<p>이제 확장기능이 설치될 것이고, Firefox가 재시작 되더라도 유지될 것입니다.</p> + +<p>대신 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext">web-ext</a> 툴을 사용해 커맨드라인에서 확장기능을 실행할 수도 있습니다.</p> + +<h3 id="테스트">테스트</h3> + +<p>이제 "mozilla.org" 페이지에 들어가 봅시다. 페이지 전체를 둘러싸고 있는 붉은 색의 테두리를 볼 수 있습니다.</p> + +<p>{{EmbedYouTube("rxBQl2Z9IBQ")}}</p> + +<div class="note"> +<p><span class="translation">addons.mozilla.org에 들어가서 테스트 하지 마세요! </span>Content script는 현재 이 도메인에 사용할 수 없도록 차단됩니다.</p> +</div> + +<p>좀 더 파고들어 봅시다. 테두리의 색을 변경하거나, 페이지 컨텐츠에 다른 것들을 해볼 수 있겠죠. content script를 저장하고 about:debugging 페이지에서 Reload 버튼을 눌러 확장기능 파일을 새로고침 할 수 있습니다. 그리고 나서는 곧바로 변경된 기능을 확인할 수 있죠.</p> + +<p>{{EmbedYouTube("NuajE60jfGY")}}</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Temporary_Installation_in_Firefox">확장기능을 불러오는 것에 대해 더 알아보기</a></li> +</ul> + +<h2 id="패키징과_배포">패키징과 배포</h2> + +<p>다른 사람들이 확장기능을 사용할 수 있게 하려면, 확장을 패키징하고 Mozilla에 제출해 서명을 받아야 합니다. <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Publishing_your_WebExtension">확장기능 배포에 대해 더 알아보기.</a></p> + +<h2 id="다음으로">다음으로</h2> + +<p>이제 어떻게 Firefox용 WebExtension을 개발해야 하는지 알게 되었습니다. 다음 글들을 읽고 시도해 보세요.</p> + +<ul> + <li><a href="/en-US/Add-ons/WebExtensions/Anatomy_of_a_WebExtension">확장기능의 구조에 대해 더 자세히 알아보기</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/Your_second_WebExtension">좀 더 복잡한 확장기능을 만들기</a></li> + <li><a href="/en-US/Add-ons/WebExtensions/API">확장기능에서 사용할 수 있는 JavaScript API 문서</a></li> +</ul> diff --git a/files/ko/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/ko/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..1d5bd49ca4 --- /dev/null +++ b/files/ko/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,456 @@ +--- +title: Your second extension +slug: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +--- +<div>{{AddonSidebar}} +<p><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension">Your first extension</a> 장을 읽었다면, 확장앱을 만드는 법을 알게 되었을 것이다. 이번 장에서는 몇개의 API를 사용하는 약간 더 복잡한 확장앱을 만들어볼 것이다.</p> + +<p>이 확장앱은 파이어폭스 툴바에 새로운 버튼을 추가한다. 사용자가 이 버튼을 클릭하면 동물을 선택하는 팝업을 보여준다. 동물을 선택하면 현재 웹페이지의 내용을 선택한 동물 이미지로 변경한다.</p> + +<p>구현내용:</p> + +<ul> + <li><strong>파이어폭스 툴바에 추가된 버튼의 <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Browser_action">browser action</a>을 정의한다. </strong><br> + 버튼을 위해 필요한것: + <ul> + <li>"beasts-32.png" 아이콘</li> + <li>버튼을 누를때 나오는 팝업. 이 팝업은 HTML과 CSS, 자바스크립트로 구성된다.</li> + </ul> + </li> + <li><strong>애드온 메니저에 보여질 확장앱 아이콘을 정의한다.</strong></li> + <li><strong>웹페이지에 주입될 "beastify.js"라는 content script를 작성한다. </strong><br> + 이것이 실제로 웹페이지를 변경할 코드이다.</li> + <li><strong>웹페이지를 변경할 동물 이미지를 패키징한다.</strong><br> + <span class="translation">이미지를 "웹 접근 가능 자원"으로 만들어 웹페이지에서 참조 하게 한다.</span></li> +</ul> + +<p>확장앱의 구조를 표현하면 아래와 같다:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/13671/Untitled-1.png" style="display: block; height: 1200px; margin-left: auto; margin-right: auto; width: 860px;"></p> + +<p><span class="translation">간단한 확장앱이지만 WebExtensions API의 기본 개념을 잘 보여줍니다.</span></p> + +<ul> + <li>툴바에 버튼 추가</li> + <li>팝업에 쓰일 HTML, CSS, 자바스크립트 정의</li> + <li>웹페이지에 content scripts 주입</li> + <li>컨텐츠 스크립트와 나머지 확장앱과의 통신</li> + <li>확장앱의 웹페이지에서 사용할 리소스 패키징</li> +</ul> + +<p><a href="https://github.com/mdn/webextensions-examples/tree/master/beastify">깃헙 예제 소스코드</a>.</p> + +<p>이 확장앱을 만드려면 파이어폭스 45이상이 필요하다.</p> + +<h2 id="Writing_the_extension">Writing the extension</h2> + +<p>새 디렉토리 생성:</p> + +<pre class="brush: bash">mkdir beastify +cd beastify</pre> + +<h3 id="manifest.json">manifest.json</h3> + +<p>이제 "manifest.json" 파일을 아래와 같은 내용으로 생성:</p> + +<pre class="brush: json">{ + + "manifest_version": 2, + "name": "Beastify", + "version": "1.0", + + "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify", + "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify", + "icons": { + "48": "icons/beasts-48.png" + }, + + "permissions": [ + "activeTab" + ], + + "browser_action": { + "default_icon": "icons/beasts-32.png", + "default_title": "Beastify", + "default_popup": "popup/choose_beast.html" + }, + + "web_accessible_resources": [ + "beasts/frog.jpg", + "beasts/turtle.jpg", + "beasts/snake.jpg" + ] + +} +</pre> + +<ul> + <li>위에서부터 세가지 키인 <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version">manifest_version</a></code>, <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name">name</a></code>, and <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version">version</a></code>는 , <span class="translation">필수항목이고 확장앱의 기본 정보이다.</span></li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description">description</a></code> 과 <code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/homepage_url">homepage_url</a></code>은 선택사항이나, 확장앱에관한 유용한 정보를 가지기에 권장한다.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/icons">icons</a></code> 도 선택사항이나 애드온 매니저에서 확장앱을 알리는 아이콘이니 권장한다.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions">permissions</a></code> 은 확장앱이 필요로 하는 권한의 목록이다. 이 확장앱에서는 <a href="/en-US/Add-ons/WebExtensions/manifest.json/permissions#activeTab_permission"><code>activeTab</code> 과 permission</a> 을 사용한다.</li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action">browser_action</a></code>는 툴바에 나오는 버튼을 정의하고 세가지 정보를 정의한다: + <ul> + <li><code>default_icon</code> 는 필수이고 , 버튼의 아이콘을 정의한다.</li> + <li><code>default_title</code> 는 선택사항이고 툴팁을 정의한다.</li> + <li><code>default_popup</code> 은 사용자가 버튼을 클릭할때 팝업을 보여주고 싶을때 사용한다. 우리는 이 항목을 추가해서 확장앱에 포함된 HTML파일을 지정한다.</li> + </ul> + </li> + <li><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources">web_accessible_resources</a></code>는 웹페이지에서 접근가능한 파일들의 목록이다. 확장앱은 이미지로 웹페이지의 컨텐츠를 변경해야하기에 이 이미지들이 페이지에 접근가능하게 해야한다.</li> +</ul> + +<p>manifest.json와 연관된 모든 경로의 것들을 기술한다.</p> + +<h3 id="The_icon">The icon</h3> + +<p>확장앱은 아이콘을 가져야한다. 이 아이콘은 애드온 매니저에서 확장앱의 목록에서 보여진다.("about:addons" url을 통해 열수 있다). 이번에 만든 manifest.json는 <span class="translation">"icons / beasts-48.png" 아이콘을 정의하였다</span></p> + +<p>"icons"라는 디렉토리를 만들고 "beasts-48.png" 파일을 그 아래에 저장한다. <span class="translation">우리 예제는 </span><a href="https://www.iconfinder.com/iconsets/free-retina-icon-set">Aha-Soft’s Free Retina iconset</a><span class="translation">에서 가져온 이미지를 </span><a href="http://www.aha-soft.com/free-icons/free-retina-icon-set/">라이센스</a><span class="translation"> 조건에 따라 사용했다.</span></p> + +<p>자신만의 아이콘을 사용하려면 48x48 픽셀이어야한다. 또한 고해상도를 위한 96x96 필셀도 지원한다. 만약 고해상도를 지원하게 하고싶다면 manifest.json의 아이콘 부분을 아래처럼 작성하면 된다.</p> + +<pre class="brush: json line-numbers language-json"><code class="language-json"><span class="key token">"icons":</span> <span class="punctuation token">{</span> + <span class="key token">"48":</span> <span class="string token">"icons/beasts-48.png"</span><span class="punctuation token">,</span> + <span class="key token">"96":</span> <span class="string token">"icons/beasts-96.png"</span> +<span class="punctuation token">}</span></code></pre> + +<h3 id="The_toolbar_button">The toolbar button</h3> + +<p>툴바 버튼도 아이콘이 필요한데, 우리 manifest.json 파일에 툴바 버튼의 아이콘을 "icons/beasts-32.png"으로 기술하였다.</p> + +<p>"icons" 디렉토리 아래 "beasts-32.png" 파일을 저장한다. 우리는 <span class="translation">우리 예제의 </span><a href="https://github.com/mdn/webextensions-examples/blob/master/beastify/icons/beasts-32.png">이미지</a><span class="translation">는 </span><a href="http://www.iconbeast.com/free">IconBeast Lite icon set</a><span class="translation">에서 가져온 이미지를 </span><a href="http://www.iconbeast.com/faq/">라이센스</a><span class="translation"> 조건에 따라 사용했다.</span></p> + +<p><span class="translation">팝업을 제공하지 않으면 사용자가 버튼을 클릭 할 때 클릭 이벤트가 없어지게된다. </span>팝업을 제공한다면 이벤트는 없이지지않고 대신 팝업이 열린다. 우리는 팝업을 열어야하니 다음에서 팝업을 정의한다.</p> + +<h3 id="The_popup">The popup</h3> + +<p>이 팝업의 기능은 세 동물중 하나를 선택하는 기능이다.</p> + +<p>확장앱 로트 아래 "popup" 디렉토리를 생성한다. 여기에대가 팝업 관련 파일들을 저장할 것 이다. 이 팝업이 가지는 세가 파일:</p> + +<ul> + <li><strong><code>choose_beast.html</code></strong> 컨텐츠의 패널 정의</li> + <li><strong><code>choose_beast.css</code></strong> 스타일</li> + <li><strong><code>choose_beast.js</code></strong> 활성화된 탭에 사용자가 선택한 이미지를 content script를 통해 반영한다.</li> +</ul> + +<pre class="brush: bash">mkdir popup +cd popup +touch choose_beast.html choose_beast.css choose_beast.js +</pre> + +<h4 id="choose_beast.html">choose_beast.html</h4> + +<p>HTML파일의 내용:</p> + +<pre class="brush: html"><!DOCTYPE html> + +<html> + <head> + <meta charset="utf-8"> + <link rel="stylesheet" href="choose_beast.css"/> + </head> + +<body> + <div id="popup-content"> + <div class="button beast">Frog</div> + <div class="button beast">Turtle</div> + <div class="button beast">Snake</div> + <div class="button reset">Reset</div> + </div> + <div id="error-content" class="hidden"> + <p>Can't beastify this web page.</p><p>Try a different page.</p> + </div> + <script src="choose_beast.js"></script> +</body> + +</html> +</pre> + +<p>각각의 동물들을 보여주는 항목을 가지는 <code><a href="/en-US/docs/Web/HTML/Element/div"><div></a></code> 요소의 ID에 <code>"popup-content"</code> 를 정의하였다. 또 다른 <code>"error-content"</code> ID를 가지는 <code><div></code>는 <code>"hidden"</code> 이라는 class를 정의하였고 팝업을 초기화 할때 문제가 생기는 경우 사용할 것이다.</p> + +<p>이 HTML파일은 일반 웹페이지처럼 CSS파일과 JS파일을 포함한다.</p> + +<h4 id="choose_beast.css">choose_beast.css</h4> + +<p>이 CSS는 팝업의 크기를 정의하고 선택항목의 공간을 정의하는등 기본적인 스타일링을 한다. 또한 <code>class="hidden"</code> 이라고 정의한 항목을 숨긴다. 이것은 <code>"error-content"</code> <code><div></code> 가 기본적으로는 숨겨진다는 것을 뜻한다.</p> + +<pre class="brush: css">html, body { + width: 100px; +} + +.hidden { + display: none; +} + +.button { + margin: 3% auto; + padding: 4px; + text-align: center; + font-size: 1.5em; + cursor: pointer; +} + +.beast:hover { + background-color: #CFF2F2; +} + +.beast { + background-color: #E5F2F2; +} + +.reset { + background-color: #FBFBC9; +} + +.reset:hover { + background-color: #EAEA9D; +} + +</pre> + +<h4 id="choose_beast.js">choose_beast.js</h4> + +<p>팝업의 자바스크립트 코드는 아래와 같다:</p> + +<pre class="brush: js">/** + * CSS to hide everything on the page, + * except for elements that have the "beastify-image" class. + */ +const hidePage = `body > :not(.beastify-image) { + display: none; + }`; + +/** + * Listen for clicks on the buttons, and send the appropriate message to + * the content script in the page. + */ +function listenForClicks() { + document.addEventListener("click", (e) => { + + /** + * Given the name of a beast, get the URL to the corresponding image. + */ + function beastNameToURL(beastName) { + switch (beastName) { + case "Frog": + return browser.extension.getURL("beasts/frog.jpg"); + case "Snake": + return browser.extension.getURL("beasts/snake.jpg"); + case "Turtle": + return browser.extension.getURL("beasts/turtle.jpg"); + } + } + + /** + * Insert the page-hiding CSS into the active tab, + * then get the beast URL and + * send a "beastify" message to the content script in the active tab. + */ + function beastify(tabs) { + browser.tabs.insertCSS({code: hidePage}).then(() => { + let url = beastNameToURL(e.target.textContent); + browser.tabs.sendMessage(tabs[0].id, { + command: "beastify", + beastURL: url + }); + }); + } + + /** + * Remove the page-hiding CSS from the active tab, + * send a "reset" message to the content script in the active tab. + */ + function reset(tabs) { + browser.tabs.removeCSS({code: hidePage}).then(() => { + browser.tabs.sendMessage(tabs[0].id, { + command: "reset", + }); + }); + } + + /** + * Just log the error to the console. + */ + function reportError(error) { + console.error(`Could not beastify: ${error}`); + } + + /** + * Get the active tab, + * then call "beastify()" or "reset()" as appropriate. + */ + if (e.target.classList.contains("beast")) { + browser.tabs.query({active: true, currentWindow: true}) + .then(beastify) + .catch(reportError); + } + else if (e.target.classList.contains("reset")) { + browser.tabs.query({active: true, currentWindow: true}) + .then(reset) + .catch(reportError); + } + }); +} + +/** + * There was an error executing the script. + * Display the popup's error message, and hide the normal UI. + */ +function reportExecuteScriptError(error) { + document.querySelector("#popup-content").classList.add("hidden"); + document.querySelector("#error-content").classList.remove("hidden"); + console.error(`Failed to execute beastify content script: ${error.message}`); +} + +/** + * When the popup loads, inject a content script into the active tab, + * and add a click handler. + * If we couldn't inject the script, handle the error. + */ +browser.tabs.executeScript({file: "/content_scripts/beastify.js"}) +.then(listenForClicks) +.catch(reportExecuteScriptError); + +</pre> + +<p>이 코드의 시작접은 96번째 라인이다. <span class="translation">이 스크립트는 browser.tabs.executeScript () API를 사용해 팝업이 로드될때 활성화된 탭에 </span>content script<span class="translation"> (</span>beastify.js<span class="translation">)를 주입한다.</span> content script<span class="translation">를 성공적으로 주입하면 사용자가 탭을 닫거나 페이지를 이동할 때까지 </span>content script<span class="translation">가 주입 된 상태로 유지된다.</span></p> + +<p><code>browser.tabs.executeScript()</code>API호출이 실패하는 공통적인 이유는 모든 웹페이지에 content scripts를 주입할 수 없기 때문이다. 예를들어 about:debugging 같은 권한이 있는 페이지에서는 content scripts를 주입할 수 없고 <a href="https://addons.mozilla.org/">addons.mozilla.org</a> 도 마찬가지이다. 이처럼 실패할때는 <code>reportExecuteScriptError()</code>가 호출되어 <code>"popup-content"</code> <code><div></code> 를 숨기고 <code>"error-content"</code> <code><div></code>를 보여주고 <a href="/en-US/Add-ons/WebExtensions/Debugging">콘솔</a>에 에러를 로깅한다.</p> + +<p>content script 주입이 성공하면 <code>listenForClicks()</code>이 호출 된다. 이 함수는 팝업에서 클릭을 위한 리스너이다.</p> + +<ul> + <li><code>"beast"</code>클래스를 가진 버튼을 클릭하면 <code>beastify()</code> 함수가 호출 된다.</li> + <li><code>"reset"</code>클래스를 가진 버튼을 클릭하면 <code>reset()</code>함수가 호출 된다.</li> +</ul> + +<p><code>beastify()</code> 함수는 3가지 기능을 한다:</p> + +<ul> + <li><span class="translation">클릭 한 버튼을 동물의 이미지 URL로 매핑</span></li> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/tabs/insertCSS">browser.tabs.insertCSS()</a></code><span class="translation"> API로 CSS를 주입하여 페이지의 전체를 숨긴다.</span></li> + <li><span class="translation">페이지를 동물그림으로 변경하도록 짐승 이미지 URL을 전달 요청하기 위해</span><code><a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/sendMessage">browser.tabs.sendMessage()</a></code><span class="translation"> API로 "beastify"메시지를 </span>content script<span class="translation">에 보낸다.</span></li> +</ul> + +<p><code>reset()</code> 함수는 페이지가 동물그림으로 변경된 것을 취소한다:</p> + +<ul> + <li><code><a href="/en-US/Add-ons/WebExtensions/API/tabs/removeCSS">browser.tabs.removeCSS()</a></code> API로 추가한 CSS를 제거한다.</li> + <li>페이지를 리셋하기 위해 content script에 "reset" 메시지를 보낸다.</li> +</ul> + +<h3 id="The_content_script">The content script</h3> + +<p>확장앱의 루트에 "content_scripts"라는 디렉토리를 생성하고, "beastify.js" 파일을 아래 내용으로 작성한다:</p> + +<pre class="brush: js">(function() { + /** + * Check and set a global guard variable. + * If this content script is injected into the same page again, + * it will do nothing next time. + */ + if (window.hasRun) { + return; + } + window.hasRun = true; + + /** + * Given a URL to a beast image, remove all existing beasts, then + * create and style an IMG node pointing to + * that image, then insert the node into the document. + */ + function insertBeast(beastURL) { + removeExistingBeasts(); + let beastImage = document.createElement("img"); + beastImage.setAttribute("src", beastURL); + beastImage.style.height = "100vh"; + beastImage.className = "beastify-image"; + document.body.appendChild(beastImage); + } + + /** + * Remove every beast from the page. + */ + function removeExistingBeasts() { + let existingBeasts = document.querySelectorAll(".beastify-image"); + for (let beast of existingBeasts) { + beast.remove(); + } + } + + /** + * Listen for messages from the background script. + * Call "beastify()" or "reset()". + */ + browser.runtime.onMessage.addListener((message) => { + if (message.command === "beastify") { + insertBeast(message.beastURL); + } else if (message.command === "reset") { + removeExistingBeasts(); + } + }); + +})(); +</pre> + +<p>content script는<span class="translation"> 먼저 전역 변수 </span><code>window.hasRun</code><span class="translation">을 확인한다:</span> content script가 이미 실행되어 있다면 아무작업도 하지 않고, 아직 주입되어 있지않으면 <code>window.hasRun</code>를 true로 셋팅한뒤 잡업을 계속한다. <span class="translation">이 작업을 하는 이유는 팝업을 열 때마다 활성화된 탭에 </span>content script<span class="translation">를 실행하기 때문에 스크립트가 중복으로 실행되기 때문에</span> 첫번째 팝업오픈시에만 content script<span class="translation">를 실행해야한다.</span></p> + +<p>그런 다음 40번째 라인에서 content script는 <span class="translation">browser.runtime.onMessage API로 팝업의 메시지를 받는다.</span> <span class="translation">위에서 봤던 팝업의 스크립트는 "beastify"와 "reset" 두 종류의 메시지를 보낸다.</span></p> + +<ul> + <li>"beastify" 메시지를 받으면 메시지에 동물이미지의 URL이 있다는 걸 예상할수 있다. <span class="translation">우리는 이전의 "beastify" 메시지로 추가 된 동물을 제거하고 <img> 요소를 만들어서 src속성에 동물 이미지 URL을 셋팅한다.</span></li> + <li>"reset" 메시지를 받으면 그냥 모든 추가된 동물을 삭제한다.</li> +</ul> + +<h3 id="The_beasts">The beasts</h3> + +<p><span class="translation">마지막으로 동물의 이미지를 추가한다.</span></p> + +<p>"beasts" 디렉토리를 만들고 그 아래 적절한 이름의 이미지 세개를 추가한다. <a href="https://github.com/mdn/webextensions-examples/tree/master/beastify/beasts">GitHub 저장소</a><span class="translation">에서 이미지를 가져올 수 있다. </span></p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/11459/frog.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"><img alt="" src="https://mdn.mozillademos.org/files/11461/snake.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"><img alt="" src="https://mdn.mozillademos.org/files/11463/turtle.jpg" style="display: inline-block; height: 200px; margin: 20px; width: 200px;"></p> + +<h2 id="Testing_it_out">Testing it out</h2> + +<p>먼저 파일들이 제자리에 있는 지 확인한다:</p> + +<pre>beastify/ + + beasts/ + frog.jpg + snake.jpg + turtle.jpg + + content_scripts/ + beastify.js + + icons/ + beasts-32.png + beasts-48.png + + popup/ + choose_beast.css + choose_beast.html + choose_beast.js + + manifest.json</pre> + +<p><span class="translation">파이어폭스 45에서 디스크로부터 임시로 확장 기능을 설치할 수 있다.</span></p> + +<p>파이어폭스에서 about:debugging를 열고 "Load Temporary Add-on"를 클릭한다음 manifest.json 파일을 선택한다. 그러면 파이어폭스 툴바에서 버튼을 볼수 있을것이다.</p> + +<p>{{EmbedYouTube("sAM78GU4P34")}}</p> + +<p>웹페이지를 열고 툴바 버튼을 클릭하고 동물을 선택하면 웹페이지가 바뀌는것을 볼 수 있을것이다.</p> + +<p>{{EmbedYouTube("YMQXyAQSiE8")}}</p> + +<h2 id="Developing_from_the_command_line">Developing from the command line</h2> + +<p>아래처럼 <a href="/en-US/Add-ons/WebExtensions/Getting_started_with_web-ext">web-ext</a>툴을 이용해 설치할 수도 있다.</p> + +<pre class="brush: bash">cd beastify +web-ext run</pre> +</div> |