diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-pt/web/api/web_workers_api | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pt-pt/web/api/web_workers_api')
3 files changed, 1768 insertions, 0 deletions
diff --git a/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html new file mode 100644 index 0000000000..ee969bfb75 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html @@ -0,0 +1,443 @@ +--- +title: Funções e classes disponíveis para os Workers da Web +slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +tags: + - Referencia + - Web +translation_of: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +--- +<p>In addition to the standard <a href="/en-US/docs/Web/JavaScript">JavaScript</a> set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc), there are a variety of functions available from the DOM to workers. This article provides a list of those.</p> + +<p><strong>Workers run in another global context, {{domxref("DedicatedWorkerGlobalScope")}}, different from the current window</strong>. By default, methods and properties of {{domxref("Window")}} are not available to them, but {{domxref("DedicatedWorkerGlobalScope")}}, like <code>Window</code>, implements {{domxref("WindowTimers")}} and {{domxref("WindowBase64")}}.</p> + +<h2 id="Comparação_das_propriedades_e_métodos_de_diferentes_tipos_de_workers">Comparação das propriedades e métodos de diferentes tipos de <em>workers</em></h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Função</td> + <td class="header">Workers dedicados</td> + <td class="header">Shared workers</td> + <td class="header">Service workers</td> + <td class="header">Chrome workers {{Non-standard_inline}}</td> + <td class="header">Outside workers</td> + </tr> + <tr> + <td>{{domxref("WindowBase64.atob", "atob()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowBase64.btoa", "btoa()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.clearInterval", "clearInterval()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("Window.dump()", "dump()")}} {{non-standard_inline}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.setInterval", "setInterval()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.setTimeout", "setTimeout()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope.importScripts", "importScripts()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>no</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope.close", "close()")}} {{non-standard_inline}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, but is a no-op.</td> + <td>Unknown</td> + <td>no</td> + </tr> + <tr> + <td>{{domxref("DedicatedWorkerGlobalScope.postMessage", "postMessage()")}}</td> + <td>yes, on {{domxref("DedicatedWorkerGlobalScope")}}</td> + <td>no</td> + <td>no</td> + <td>Unknown</td> + <td>no</td> + </tr> + </tbody> +</table> + +<h2 id="APIs_disponíveis_nos_workers">APIs disponíveis nos <em>workers</em></h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Função</td> + <td class="header">Funcionalidade</td> + <td class="header">Suporte no Gecko (Firefox)</td> + <td class="header">Support in IE</td> + <td class="header">Support in Blink (Chrome and Opera)</td> + <td class="header">Support in WebKit (Safari)</td> + </tr> + <tr> + <td>{{domxref("Broadcast_Channel_API","Broadcast Channel API")}}</td> + <td>Allows simple communication between {{glossary("browsing context", "browsing contexts")}} (that is <em>windows</em>, <em>tabs</em>, <em>frames</em>, or <em>iframes</em>) with the same {{glossary("origin")}} (usually pages from the same site).</td> + <td>{{ CompatGeckoDesktop(38)}}</td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Cache", "Cache")}}</span></td> + <td>Cache API<span style="background-color: rgba(212, 221, 228, 0.14902);"> provides the ability to programmatically</span> control cache storage associated with current origin.</td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatVersionUnknown}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{ CompatChrome(43) }}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatUnknown}}</span></td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Channel_Messaging_API", "Channel Messaging API")}}</span></td> + <td>Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a {{domxref("SharedWorker")}}, or two workers) to communicate directly via two ports.</td> + <td>{{ CompatGeckoDesktop(41)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Console", "Console API")}}</span></td> + <td>Provides access to the browser's debugging console (e.g., the <a href="/en-US/docs/Tools/Web_Console">Web Console</a> in Firefox). The specifics of how it works vary from browser to browser, but there is a <em>de facto</em> set of features that are typically provided.</td> + <td>{{ CompatGeckoDesktop(38)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("CustomEvent")}}</span></td> + <td>The <strong><code>CustomEvent</code></strong> interface represents events initialized by an application for any purpose.</td> + <td>{{ CompatGeckoDesktop(48)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Data_Store_API", "Data Store")}}</td> + <td>A powerful, flexible storage mechanism for multiple Firefox OS applications to use to store and share data between one another quickly, efficiently, and securely.</td> + <td>Only in Firefox OS internal (certified) applications, since v1.0.1.</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("DOMRequest")}} and {{domxref("DOMCursor")}}</td> + <td>Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.</td> + <td>{{ CompatGeckoDesktop(41)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Fetch_API", "Fetch")}}</td> + <td>The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.)</td> + <td>Mostly in {{ CompatGeckoDesktop(34)}} behind pref, although a few features are later.</td> + <td>{{CompatNo}}</td> + <td>{{ CompatChrome(42) }}<br> + {{ CompatChrome(41) }} behind pref</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FileReader")}}</td> + <td>This API allows asynchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects.</td> + <td>{{CompatGeckoDesktop(46)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FileReaderSync")}}</td> + <td>This API allows synchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects. This is an API that works only in workers.</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FormData")}}</td> + <td><code>FormData</code> objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest <a href="/en-US/docs/DOM/XMLHttpRequest#send()" title="XMLHttpRequest#send()"><code>send()</code></a> method.</td> + <td>{{CompatUnknown}} (should be in {{CompatGeckoDesktop(39)}})</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("ImageData")}}</td> + <td>The underlying pixel data of an area of a {{domxref("canvas")}} element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker.</td> + <td>{{CompatGeckoDesktop(25)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("IndexedDB_API", "IndexedDB")}}</td> + <td>Database to store records holding simple values and hierarchical objects.</td> + <td>{{CompatGeckoDesktop(37)}}, {{CompatGeckoDesktop(42)}} for {{domxref("IDBCursorWithValue")}}.</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/Network_Information_API">Network Information API</a></td> + <td>provides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.).</td> + <td>{{CompatGeckoMobile(53)}} only on mobile</td> + <td>{{CompatVersionUnknown}} only on mobile</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("Notifications_API", "Notifications")}}</td> + <td>Allows web pages to control the display of system notifications to the end user</td> + <td>{{CompatGeckoDesktop(41)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Performance")}}</td> + <td>The <strong><code>Performance</code></strong> interface represents timing-related performance information for the given page.</td> + <td>{{ CompatGeckoDesktop("34.0") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatChrome("33.0") }}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{jsxref("Promise")}}</td> + <td>JavaScript objects that allow you to write asynchronous functions.</td> + <td>{{CompatGeckoDesktop(28)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/Server-sent_events">Server-sent events</a></td> + <td>Allows a server to push data to a web page at any point, after a connection has been opened to it.</td> + <td>{{CompatGeckoDesktop(53)}} (currently only available in dedicated and shared workers; not service workers.)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerRegistration")}}</td> + <td>You can register a service worker from inside a standard worker, and use associated functionality.</td> + <td>{{CompatGeckoDesktop(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("TextEncoder")}} and {{domxref("TextDecoder")}}</td> + <td>Create and return a new {{domxref("TextEncoder")}}, or respectively {{domxref("TextDecoder")}}, allowing to encode or decode strings into specific encodings.</td> + <td>{{CompatGeckoDesktop(20)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{ domxref("URL") }}</td> + <td>Workers can use the static methods <a href="/en-US/docs/DOM/window.URL.createObjectURL" title="/en-US/docs/DOM/window.URL.createObjectURL">URL.createObjectURL</a> and <a href="/en-US/docs/DOM/window.URL.revokeObjectURL" title="/en-US/docs/DOM/window.URL.revokeObjectURL">URL.revokeObjectURL</a> with {{domxref("Blob")}} objects accesible to the worker.<br> + Workers can also create a new URL using the {{domxref("URL.URL", "URL()")}} constructor and call any normal method on the returned object.</td> + <td>{{CompatGeckoDesktop(21)}} and {{CompatGeckoDesktop(26)}} for URL() constructor</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/WebGL_API">WebGL</a> with {{domxref("OffscreenCanvas")}}</td> + <td>WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.</td> + <td>{{CompatGeckoDesktop(44)}} behind a feature preference setting. In <code>about:config</code>, set <code>gfx.offscreencanvas.enabled</code> to true.</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("WebSocket")}}</td> + <td>Creates and returns a new {{domxref("WebSocket")}} object; this mimics the behavior of the standard <code>WebSocket()</code> constructor.</td> + <td>{{CompatGeckoDesktop(37)}}</td> + <td>11.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Worker")}}</td> + <td>Creates a new {{ domxref("Worker") }}. Yes, workers can spawn more workers.</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10.0</td> + <td>{{CompatNo}} See <a class="external" href="https://code.google.com/p/chromium/issues/detail?id=31666" rel="external" title="http://code.google.com/p/chromium/issues/detail?id=31666">crbug.com/31666</a></td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope")}}</td> + <td>The global scope of workers. This objects defines <a href="#workerscope">worker-specific functions</a>.</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("WorkerLocation")}}</td> + <td>The subset of the {{domxref("Location")}} interface available to workers.</td> + <td>{{CompatGeckoDesktop(1.9.2)}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("WorkerNavigator")}}</td> + <td>The subset of the {{domxref("Navigator")}} interface available to workers.</td> + <td>Basic implementation {{CompatVersionUnknown}}<br> + {{domxref("NavigatorID.appCodeName", "appCodeName")}}, {{domxref("NavigatorID.product", "product")}}, {{domxref("NavigatorID.taintEnabled", "taintEnabled()")}}: {{CompatGeckoDesktop(28)}}<br> + {{domxref("WorkerNavigator.onLine", "onLine")}}: {{CompatGeckoDesktop(29)}}<br> + {{domxref("NavigatorLanguage")}}: {{CompatVersionUnknown}}</td> + <td>{{domxref("NavigatorID.appName", "appName")}}, {{domxref("NavigatorID.appVersion", "appVersion")}}, {{domxref("WorkerNavigator.onLine", "onLine")}}, {{domxref("NavigatorID.platform", "platform")}}, {{domxref("NavigatorID.userAgent", "userAgent")}}: 10.0<br> + Other: {{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("XMLHttpRequest")}}</td> + <td>Creates and returns a new {{domxref("XMLHttpRequest")}} object; this mimics the behavior of the standard <code>XMLHttpRequest()</code> constructor. Note that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</td> + <td> + <p>Basic: {{CompatGeckoDesktop("1.9.1")}}</p> + + <p>{{domxref("XMLHttpRequest.response", "response")}} and {{domxref("XMLHttpRequest.responseType", "responseType")}} are available since {{CompatGeckoDesktop("10")}}</p> + + <p>{{domxref("XMLHttpRequest.timeout", "timeout")}} and {{domxref("XMLHttpRequest.ontimeout", "ontimeout")}} are available since {{CompatGeckoDesktop("13")}}</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/Web_Workers_API/Utilizacao_de_web_workers">Utilização de workers da Web</a></li> + <li>{{domxref("Worker")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/web_workers_api/index.html b/files/pt-pt/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..9c1040b06f --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/index.html @@ -0,0 +1,234 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +tags: + - API + - NeedsTranslation + - Service Workers + - Shared Workers + - TopicStub + - Web Workers + - Workers +translation_of: Web/API/Web_Workers_API +--- +<p>{{DefaultAPISidebar("Web Workers API")}}</p> + +<p class="summary"><strong>Web Workers</strong> makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.</p> + +<h2 id="Web_Workers_concepts_and_usage">Web Workers concepts and usage</h2> + +<p>A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. This context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}).</p> + +<p>You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under <code>window</code>, including <a href="/en-US/docs/WebSockets">WebSockets</a>, and data storage mechanisms like <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and the Firefox OS-only <a href="/en-US/docs/Web/API/Data_Store_API">Data Store API</a>. See <a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a> for more details.</p> + +<p>Data is sent between workers and the main thread via a system of messages — both sides send their messages using the <code>postMessage()</code> method, and respond to messages via the <code>onmessage</code> event handler (the message is contained within the {{event("Message")}} event's <code>data</code> property). The data is copied rather than shared.</p> + +<p>Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use <a class="internal" href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> for network I/O, with the exception that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</p> + +<p>In addition to dedicated workers, there are other types of worker:</p> + +<ul> + <li>Shared workers are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port. See {{domxref("SharedWorker")}} for more details.</li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorkers</a> essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.</li> + <li>Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to <a href="https://developer.mozilla.org/en/js-ctypes">js-ctypes</a> in your worker. See {{domxref("ChromeWorker")}} for more details. </li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API#Audio_Workers">Audio Workers</a> provide the ability for direct scripted audio processing to be done inside a web worker context.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: As per the <a href="https://html.spec.whatwg.org/multipage/workers.html#runtime-script-errors-2">Web workers Spec</a>, worker error events should not bubble (see {{bug(1188141)}}. This has been implemented in Firefox 42.</p> +</div> + +<h2 id="Web_Worker_interfaces">Web Worker interfaces</h2> + +<dl> + <dt>{{domxref("AbstractWorker")}}</dt> + <dd>Abstracts properties and methods common to all kind of workers (i.e. {{domxref("Worker")}} or {{domxref("SharedWorker")}}).</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Represents a running worker thread, allowing you to pass messages to the running worker code.</dd> + <dt>{{domxref("WorkerLocation")}}</dt> + <dd>Defines the absolute location of the script executed by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker" title="The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread."><code>Worker</code></a>.</dd> +</dl> + +<dl> + <dt>{{domxref("SharedWorker")}}</dt> + <dd>Represents a specific kind of worker that can be <em>accessed</em> from several browsing contexts, being several windows, iframes or even workers.</dd> + <dt>{{domxref("WorkerGlobalScope")}}</dt> + <dd>Represents the generic scope of any worker (doing the same job as {{domxref("Window")}} does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.</dd> + <dt>{{domxref("DedicatedWorkerGlobalScope")}}</dt> + <dd>Represents the scope of a dedicated worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.</dd> + <dt>{{domxref("SharedWorkerGlobalScope")}}</dt> + <dd>Represents the scope of a shared worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.</dd> + <dt>{{domxref("WorkerNavigator")}}</dt> + <dd>Represents the identity and state of the user agent (the client):</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>We have created a couple of simple demos to show basic usage:</p> + +<ul> + <li><a href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</li> + <li><a href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a href="http://mdn.github.io/simple-shared-worker/">run shared worker</a>).</li> +</ul> + +<p>You can find out more information on how these demos work in <a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#workers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.9.1)}}</td> + <td>10.0</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Shared workers</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatNo}}</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Passing data using structured cloning</td> + <td>13</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>10.0</td> + <td>11.5</td> + <td>6</td> + </tr> + <tr> + <td>Passing data using transferable objects</td> + <td>17 {{property_prefix("webkit")}}<br> + 21</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(18)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>6</td> + </tr> + <tr> + <td>Global {{domxref("window.URL", "URL")}}</td> + <td>10<sup>[1]</sup><br> + 23</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>11</td> + <td>15</td> + <td>6<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.9.1)}}</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + </tr> + <tr> + <td>Shared workers</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>29</td> + <td>1.4</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using structured cloning</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using transferable objects</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>18</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] As <code>webkitURL</code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/basic_usage">Using Web Workers</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker Interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker">SharedWorker interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Advanced_concepts_and_examples">Advanced concepts and examples</a></li> + <li><a href="/en-US/docs/Web/API/ChromeWorker">ChromeWorker</a>: for using workers in privileged/chrome code</li> +</ul> diff --git a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html new file mode 100644 index 0000000000..d9705559e7 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html @@ -0,0 +1,1091 @@ +--- +title: Utilização de Web Workers +slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers +tags: + - Avançado + - Firefox + - Guía + - JavaScript + - Operadores + - Workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +<div class="summary"> +<p><em>Web Workers</em> é um meio simples para o conteúdo da Web para executar <em>scripts</em> em segmentos em segundo plano. O segmento do <em>worker</em> pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando <code><a class="internal" href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest">XMLHttpRequest</a></code> (embora<code> e responseXML</code> e os atributos de <code>channel</code> são sempre nulos). Uma vez criado, um <em>worker </em>pode enviar mensagens para o código JavaScript que o criou publicando mensagens para um manipulador de evento especificado por esse código (e vice-versa.) Este artigo fornece uma introdução detalhada para utilizar <em>workers </em>da Web.</p> +</div> + +<h2 id="API_de_Workers_da_Web">API de Workers da Web</h2> + +<p>A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error.</p> + +<p>The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.</p> + +<div class="note"> +<p><strong>Nota</strong>: See <a href="/en-US/docs/Web/API/Web_Workers_API">The Web Workers API landing page</a> for reference documentation on workers and additional guides.</p> +</div> + +<p>You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under <code>window</code>, including <a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a>, and data storage mechanisms like <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and the Firefox OS-only <a href="/en-US/docs/Web/API/Data_Store_API">Data Store API</a>. See <a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a> for more details.</p> + +<p>Data is sent between workers and the main thread via a system of messages — both sides send their messages using the <code>postMessage()</code> method, and respond to messages via the <code>onmessage</code> event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.</p> + +<p>Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use <a class="internal" href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> for network I/O, with the exception that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</p> + +<h2 id="Workers_dedicados">Workers dedicados</h2> + +<p>As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our <a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" href="https://mdn.github.io/simple-web-worker/">run dedicated worker</a>): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.</p> + +<p>This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.</p> + +<h3 id="Detecção_da_funcionalidade_worker">Detecção da funcionalidade worker</h3> + +<p>For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<pre class="brush: js">if (window.Worker) { + + ... + +}</pre> + +<h3 id="Geração_de_um_worker_dedicado">Geração de um <em>worker </em>dedicado</h3> + +<p>Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<div style="overflow: hidden;"> +<pre class="brush: js">var myWorker = new Worker('worker.js'); +</pre> +</div> + +<h3 id="Enviar_mensagens_para_e_de_um_worker_dedicado">Enviar mensagens para /e de um <em>worker </em>dedicado</h3> + +<p>The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<pre class="brush: js">first.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +} + +second.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +}</pre> + +<p>So here we have two {{htmlelement("input")}} elements represented by the variables <code>first</code> and <code>second</code>; when the value of either is changed, <code>myWorker.postMessage([first.value,second.value])</code> is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.</p> + +<p>In the worker, we can respond when the message is received by writing an event handler block like this (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/worker.js">worker.js</a>):</p> + +<pre class="brush: js">onmessage = function(e) { + console.log('Message received from main script'); + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + console.log('Posting message back to main script'); + postMessage(workerResult); +}</pre> + +<p>The <code>onmessage</code> handler allows us to run some code whenever a message is received, with the message itself being available in the <code>message</code> event's <code>data</code> attribute. Here we simply multiply together the two numbers then use <code>postMessage()</code> again, to post the result back to the main thread.</p> + +<p>Back in the main thread, we use <code>onmessage</code> again, to respond to the message sent back from the worker:</p> + +<pre class="brush: js">myWorker.onmessage = function(e) { + result.textContent = e.data; + console.log('Message received from worker'); +}</pre> + +<p>Here we grab the message event data and set it as the <code>textContent</code> of the result paragraph, so the user can see the result of the calculation.</p> + +<div class="note"> +<p><strong>Nota</strong>: The URI passed as a parameter to the <code>Worker</code> constructor must obey the <a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a> .</p> + +<p>There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.</p> +</div> + +<div class="note"><strong>Nota</strong>: Notice that <code>onmessage</code> and <code>postMessage()</code> need to be hung off the <code>Worker</code> object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.</div> + +<div class="note"><strong>Nota</strong>: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.</div> + +<h3 id="Terminar_um_worker">Terminar um <em>worker</em></h3> + +<p>If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:</p> + +<pre class="brush: js">myWorker.terminate();</pre> + +<p>The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.</p> + +<p>In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:</p> + +<pre class="brush: js">close();</pre> + +<h3 id="Lidar_com_erros">Lidar com erros</h3> + +<p>When a runtime error occurs in the worker, its <code>onerror</code> event handler is called. It receives an event named <code>error</code> which implements the <code>ErrorEvent</code> interface.</p> + +<p>The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's <a class="internal" href="/en-US/docs/Web/API/Event/preventDefault"> <code>preventDefault()</code> </a> method.</p> + +<p>The error event has the following three fields that are of interest:</p> + +<dl> + <dt><code>message</code></dt> + <dd>A human-readable error message.</dd> + <dt><code>filename</code></dt> + <dd>The name of the script file in which the error occurred.</dd> + <dt><code>lineno</code></dt> + <dd>The line number of the script file on which the error occurred.</dd> +</dl> + +<h3 id="Gerar_subworkers">Gerar <em>subworkers</em></h3> + +<p>Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.</p> + +<h3 id="Importar_scripts_e_bibliotecas">Importar <em>scripts</em> e bibliotecas</h3> + +<p>Worker threads have access to a global function, <code>importScripts()</code>, which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:</p> + +<pre class="brush: js">importScripts(); /* imports nothing */ +importScripts('foo.js'); /* imports just "foo.js" */ +importScripts('foo.js', 'bar.js'); /* imports two scripts */ +importScripts('//example.com/hello.js'); /* You can import scripts from other origins */</pre> + +<p>The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, <code>NETWORK_ERROR</code> is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations <strong>after</strong> the <code>importScripts()</code> method are also kept, since these are always evaluated before the rest of the code.</p> + +<div class="note"><strong>Note</strong>: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into <code>importScripts()</code> . This is done synchronously; <code>importScripts()</code> does not return until all the scripts have been loaded and executed.</div> + +<h2 id="Shared_workers_(Partilhados)"><em>Shared workers (Partilhados)</em></h2> + +<p>A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our <a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a class="external external-icon" href="https://mdn.github.io/simple-shared-worker/">run shared worker</a>): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: <em>multiplying two numbers</em>, or <em>squaring a number</em>. Both scripts use the same worker to do the actual calculation required.</p> + +<p>Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.</p> + +<div class="note"> +<p><strong>Nota</strong>: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).</p> +</div> + +<h3 id="Gerar_um_shared_worker">Gerar um <em>shared worker</em></h3> + +<p>Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/index.html">index.html</a> and <a href="https://mdn.github.io/simple-shared-worker/index2.html">index2.html</a>) — each one has to spin up the worker using code like the following:</p> + +<pre class="brush: js">var myWorker = new SharedWorker('worker.js');</pre> + +<p>One big difference is that with a shared worker you have to communicate via a <code>port</code> object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).</p> + +<p>The port connection needs to be started either implicitly by use of the <code>onmessage </code>event handler or explicitly with the <code>start()</code> method before any messages can be posted. Although the <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/worker.js">worker.js</a> files in the demo currently call the <code>start()</code> method, those calls are not necessary since the <code>onmessage</code> event handler is being used. Calling <code>start()</code> is only needed if the <code>message</code> event is wired up via the <code>addEventListener()</code> method.</p> + +<p>When using the <code>start()</code> method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.</p> + +<pre class="brush: js">myWorker.port.start(); // called in parent thread</pre> + +<pre class="brush: js">port.start(); // called in worker thread, assuming the <code>port</code> variable references a port</pre> + +<h3 id="Enviar_mensagens_parae_de_um_shared_worker">Enviar mensagens para/e de um <em>shared worker</em></h3> + +<p>Now messages can be sent to the worker as before, but the <code>postMessage()</code> method has to be invoked through the port object (again, you'll see similar constructs in both <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/square.js">square.js</a>):</p> + +<pre class="brush: js">squareNumber.onchange = function() { + myWorker.port.postMessage([squareNumber.value,squareNumber.value]); + console.log('Message posted to worker'); +}</pre> + +<p>Now, on to the worker. There is a bit more complexity here as well (<a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/worker.js">worker.js</a>):</p> + +<pre class="brush: js">onconnect = function(e) { + var port = e.ports[0]; + + port.onmessage = function(e) { + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + port.postMessage(workerResult); + } +}</pre> + +<p>First, we use an <code>onconnect</code> handler to fire code when a connection to the port happens (i.e. when the <code>onmessage</code> event handler in the parent thread is setup, or when the <code>start()</code> method is explicitly called in the parent thread).</p> + +<p>We use the <code>ports</code> attribute of this event object to grab the port and store it in a variable.</p> + +<p>Next, we add a <code>message</code> handler on the port to do the calculation and return the result to the main thread. Setting up this <code>message</code> handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to <code>port.start()</code> is not actually needed, as noted above.</p> + +<p>Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/square.js">square.js</a>):</p> + +<pre class="brush: js">myWorker.port.onmessage = function(e) { + result2.textContent = e.data; + console.log('Message received from worker'); +}</pre> + +<p>When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.</p> + +<h2 id="Sobre_a_segurança_de_segmento">Sobre a segurança de segmento</h2> + +<p>The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.</p> + +<p>However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.</p> + +<p>An example of a catastrophy would be like the following:</p> + +<h3 id="Conteúdo_HTML">Conteúdo HTML</h3> + +<pre class="brush: html"><html> +<head> +<title>Multithreading Catastrophy</title> +<style> +body { margin: 0px; } +canvas { position: absolute; top: 0; bottom: 0; left: 0; right:0; width: 100%; height: 100%; } +</style> +<script src="main.js" async></script> +</head> +<body> +<canvas id="canvas"></canvas> +</body> +</html></pre> + +<h3 id="Conteúdo_main.js">Conteúdo main.js</h3> + +<pre class="brush: js">// main.js +var myworker = new Worker("worker.js"), width=window.innerWidth, height=window.innerHeight, context=document.getElementById('canvas').getContext('2d'); +var imagedatatmp=context.createImageData(width,height); + +myworker.onmessage = function(data){ + imageData = imagedatatmp.from(data); +}; + +setTimeout(function draw_canvas() { + context.putImageData(imageData); + setTimeout(draw_canvas, 1000/60); +},10); + +window.onresize = window.reload; // Quick (to type) n' dirty way to resize;</pre> + +<h3 id="Conteúdo_worker.js">Conteúdo worker.js</h3> + +<pre class="brush: js">// worker.js +window.onmessage = function(width, height){ +var noise = function(x, y, z) { + var p = new Array(512), permutation = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]; + for (var i = 0;i < 256;i++) p[256 + i] = p[i] = permutation[i]; + var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x), y -= Math.floor(y), z -= Math.floor(z); + var u = fade(x), v = fade(y), w = fade(z); + var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z; + return scale(lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1))))); +}; + function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } + function lerp(t, a, b) { return a + t * (b - a); } + function grad(hash, x, y, z) { + var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); + } + function scale(n) { return (1 + n) / 2; } +var length = width*height; var canvasnoisedata=new UInt32Array(length); + +setTimeout(function make_noise() { +var i=length, z=Math.random()*1024; + while ( i-- ) { + canvasnoisedata[i] = noise(i%width+z,i/width+z,z); + } + setTimeout(make_noise, 1000/60); +},1000/60); + +setTimeout(function post_noise() { + postMessage( canvasnoisedata ); + setTimeout(post_noise, 1000/60); +},1000/60); +}; +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{ EmbedLiveSample('ats.html') }}</p> + +<h2 id="Política_de_segurança_de_conteúdo">Política de segurança de conteúdo</h2> + +<p>Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">content security policy</a> of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:</p> + +<pre>Content-Security-Policy: script-src 'self'</pre> + +<div>Among other things, this will prevent any scripts it includes from using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a></code>. However, if the script constructs a worker, code running in the worker's context <em>will</em> be allowed to use <code>eval()</code>.<br> +<br> +To specify a content security policy for the worker, set a <a href="/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">Content-Security-Policy</a> response header for the request which delivered the worker script itself.<br> +<br> +The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it.</div> + +<div> </div> + +<h2 id="Transferir_dados_parae_de_workers_detalhes_adicionais">Transferir dados para/e de <em>workers</em>: detalhes adicionais</h2> + +<p>Data passed between the main page and workers is <strong>copied</strong>, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker <strong>do not share the same instance</strong>, so the end result is that <strong>a duplicate</strong> is created on each end. Most browsers implement this feature as <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a>.</p> + +<p>To illustrate this, let's create for didactical purpose a function named <code>emulateMessage()</code>, which will simulate the behavior of a value that is <em>cloned and not shared</em> during the passage from a <code>worker</code> to the main page or vice versa:</p> + +<pre class="brush: js">function emulateMessage(vVal) { + return eval('(' + JSON.stringify(vVal) + ')'); +} + +// Tests + +// test #1 +var example1 = new Number(3); +console.log(typeof example1); // object +console.log(typeof emulateMessage(example1)); // number + +// test #2 +var example2 = true; +console.log(typeof example2); // boolean +console.log(typeof emulateMessage(example2)); // boolean + +// test #3 +var example3 = new String('Hello World'); +console.log(typeof example3); // object +console.log(typeof emulateMessage(example3)); // string + +// test #4 +var example4 = { + 'name': 'John Smith', + "age": 43 +}; +console.log(typeof example4); // object +console.log(typeof emulateMessage(example4)); // object + +// test #5 +function Animal(sType, nAge) { + this.type = sType; + this.age = nAge; +} +var example5 = new Animal('Cat', 3); +alert(example5.constructor); // Animal +alert(emulateMessage(example5).constructor); // Object</pre> + +<p>A value that is cloned and not shared is called <em>message</em>. As you will probably know by now, <em>messages</em> can be sent to and from the main thread by using <code>postMessage()</code>, and the <code>message</code> event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.</p> + +<p><strong>example.html</strong>: (a página principal):</p> + +<pre class="brush: js">var myWorker = new Worker('my_task.js'); + +myWorker.onmessage = function(oEvent) { + console.log('Worker said : ' + oEvent.data); +}; + +myWorker.postMessage('ali');</pre> + +<p><strong>my_task.js</strong> (o <em>worker</em>):</p> + +<pre class="brush: js">postMessage("I\'m working before postMessage(\'ali\')."); + +onmessage = function(oEvent) { + postMessage('Hi ' + oEvent.data); +};</pre> + +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a> algorithm can accept JSON and a few things that JSON can't — like circular references.</p> + +<h3 id="Passagem_de_exemplos_de_dados">Passagem de exemplos de dados</h3> + +<h4 id="Exemplo_1_Criar_um_genérico_assíncrono_eval()">Exemplo #1: Criar um genérico "assíncrono <code>eval()</code>"</h4> + +<p>The following example shows how to use a worker in order to <strong>asynchronously</strong> execute any JavaScript code allowed in a worker, through <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> within the worker:</p> + +<pre class="brush: js">// Syntax: asyncEval(code[, listener]) + +var asyncEval = (function () { + var aListeners = [], oParser = new Worker('data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D'); + + oParser.onmessage = function(oEvent) { + if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); } + delete aListeners[oEvent.data.id]; + }; + + return function(sCode, fListener) { + aListeners.push(fListener || null); + oParser.postMessage({ + 'id': aListeners.length - 1, + 'code': sCode + }); + }; +})();</pre> + +<p>The <a href="/en-US/docs/Web/HTTP/data_URIs">data URL</a> is equivalent to a network request, with the following response:</p> + +<pre class="brush: js">onmessage = function(oEvent) { + postMessage({ + 'id': oEvent.data.id, + 'evaluated': eval(oEvent.data.code) + }); +}</pre> + +<p>Amostra de utilização:</p> + +<pre class="brush: js">// asynchronous alert message... +asyncEval('3 + 2', function(sMessage) { + alert('3 + 2 = ' + sMessage); +}); + +// asynchronous print message... +asyncEval("\"Hello World!!!\"", function(sHTML) { + document.body.appendChild(document.createTextNode(sHTML)); +}); + +// asynchronous void... +asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");</pre> + +<h4 id="Exemplo_2_Passagem_avançada_da_'Dados'_JSON_e_criar_um_sistema_de_troca">Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca</h4> + +<p>If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.</p> + +<p>First, we create a QueryableWorker class that takes the <font face="Consolas, Liberation Mono, Courier, monospace">url</font> of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker:</p> + +<pre class="brush: js">function QueryableWorker(url, defaultListener, onError) { + var instance = this, + worker = new Worker(url), + listeners = {}; + + this.defaultListener = defaultListener || function() {}; + + if (onError) {worker.onerror = onError;} + + this.postMessage = function(message) { + worker.postMessage(message); + } + + this.terminate = function() { + worker.terminate(); + } +}</pre> + +<p>Then we add the methods of adding/removing listeners:</p> + +<pre class="brush: js">this.addListeners = function(name, listener) { + listeners[name] = listener; +} + +this.removeListeners = function(name) { + delete listeners[name]; +}</pre> + +<p>Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.</p> + +<pre class="brush: js">/* + This functions takes at least one argument, the method name we want to query. + Then we can pass in the arguments that the method needs. + */ +this.sendQuery = function() { + if (arguments.length < 1) { + throw new TypeError('QueryableWorker.sendQuery takes at least one argument'); + return; + } + worker.postMessage({ + 'queryMethod': arguments[0], + 'queryArguments': Array.prototype.slice.call(arguments, 1) + }); +}</pre> + +<p>We finish QueryableWorker with the <code>onmessage</code> method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in <code>listeners</code>.:</p> + +<pre class="brush: js">worker.onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethodListener') && + event.data.hasOwnProperty('queryMethodArguments')) { + listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments); + } else { + this.defaultListener.call(instance, event.data); + } +} +</pre> + +<p>Now onto the worker. First we need to have the methods to handle the two simple operations:</p> + +<pre class="brush: js">var queryableFunctions = { + getDifference: function(a, b) { + reply('printStuff', a - b); + }, + waitSomeTime: function() { + setTimeout(function() { + reply('doAlert', 3, 'seconds'); + }, 3000); + } +} + +function reply() { + if (arguments.length < 1) { + throw new TypeError('reply - takes at least one argument'); + return; + } + postMessage({ + queryMethodListener: arguments[0], + queryMethodArguments: Array.prototype.slice.call(arguments, 1) + }); +} + +/* This method is called when main page calls QueryWorker's postMessage method directly*/ +function defaultReply(message) { + // do something +} +</pre> + +<p>And the <code>onmessage</code> method is now trivial:</p> + +<pre class="brush: js">onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethod') && + event.data.hasOwnProperty('queryMethodArguments')) { + queryableFunctions[event.data.queryMethod] + .apply(self, event.data.queryMethodArguments); + } else { + defaultReply(event.data); + } +} +</pre> + +<p>Here are the full implementation:</p> + +<p><strong>example.html</strong> (the main page):</p> + +<pre class="brush: html"><!doctype html> + <html> + <head> + <meta charset="UTF-8" /> + <title>MDN Example - Queryable worker</title> + <script type="text/javascript"> + /* + QueryableWorker instances methods: + * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function + * postMessage(string or JSON Data): see Worker.prototype.postMessage() + * terminate(): terminates the Worker + * addListener(name, function): adds a listener + * removeListener(name): removes a listener + QueryableWorker instances properties: + * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly + */ + function QueryableWorker(url, defaultListener, onError) { + var instance = this, + worker = new Worker(url), + listeners = {}; + + this.defaultListener = defaultListener || function() {}; + + if (onError) {worker.onerror = onError;} + + this.postMessage = function(message) { + worker.postMessage(message); + } + + this.terminate = function() { + worker.terminate(); + } + + this.addListener = function(name, listener) { + listeners[name] = listener; + } + + this.removeListener = function(name) { + delete listeners[name]; + } + + /* + This functions takes at least one argument, the method name we want to query. + Then we can pass in the arguments that the method needs. + */ + this.sendQuery = function() { + if (arguments.length < 1) { + throw new TypeError('QueryableWorker.sendQuery takes at least one argument'); + return; + } + worker.postMessage({ + 'queryMethod': arguments[0], + 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) + }); + } + + worker.onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethodListener') && + event.data.hasOwnProperty('queryMethodArguments')) { + listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments); + } else { + this.defaultListener.call(instance, event.data); + } + } + } + + // your custom "queryable" worker + var myTask = new QueryableWorker('my_task.js'); + + // your custom "listeners" + myTask.addListener('printStuff', function (result) { + document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!')); + }); + + myTask.addListener('doAlert', function (time, unit) { + alert('Worker waited for ' + time + ' ' + unit + ' :-)'); + }); +</script> +</head> +<body> + <ul> + <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li> + <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li> + <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li> + </ul> +</body> +</html></pre> + +<p><strong>my_task.js</strong> (o <em>worker</em>):</p> + +<pre class="brush: js">var queryableFunctions = { + // example #1: get the difference between two numbers: + getDifference: function(nMinuend, nSubtrahend) { + reply('printStuff', nMinuend - nSubtrahend); + }, + // example #2: wait three seconds + waitSomeTime: function() { + setTimeout(function() { reply('doAlert', 3, 'seconds'); }, 3000); + } +}; + +// system functions + +function defaultReply(message) { + // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly + // do something +} + +function reply() { + if (arguments.length < 1) { throw new TypeError('reply - not enough arguments'); return; } + postMessage({ 'queryMethodListener': arguments[0], 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) }); +} + +onmessage = function(oEvent) { + if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) { + queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments); + } else { + defaultReply(oEvent.data); + } +};</pre> + +<p>It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in <code>QueryableWorker</code> and the <code>worker</code>.</p> + +<h3 id="Passing_data_by_transferring_ownership_(transferable_objects)">Passing data by transferring ownership (transferable objects)</h3> + +<p>Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.</p> + +<pre class="brush: js">// Create a 32MB "file" and fill it. +var uInt8Array = new Uint8Array(1024 * 1024 * 32); // 32MB +for (var i = 0; i < uInt8Array.length; ++i) { + uInt8Array[i] = i; +} + +worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: For more information on transferable objects, performance, and feature-detection for this method, read <a href="http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast">Transferable Objects: Lightning Fast!</a> on HTML5 Rocks.</p> +</div> + +<h2 id="Workers_integrados">Workers integrados</h2> + +<p>There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a <code>src</code> attribute and has a <code>type</code> attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> +<head> +<meta charset="UTF-8" /> +<title>MDN Example - Embedded worker</title> +<script type="text/js-worker"> + // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. + var myVar = 'Hello World!'; + // Rest of your worker code goes here. +</script> +<script type="text/javascript"> + // This script WILL be parsed by JS engines because its MIME type is text/javascript. + function pageLog(sMsg) { + // Use a fragment: browser will only render/reflow once. + var oFragm = document.createDocumentFragment(); + oFragm.appendChild(document.createTextNode(sMsg)); + oFragm.appendChild(document.createElement('br')); + document.querySelector('#logDisplay').appendChild(oFragm); + } +</script> +<script type="text/js-worker"> + // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. + onmessage = function(oEvent) { + postMessage(myVar); + }; + // Rest of your worker code goes here. +</script> +<script type="text/javascript"> + // This script WILL be parsed by JS engines because its MIME type is text/javascript. + + // In the past...: + // blob builder existed + // ...but now we use Blob...: + var blob = new Blob(Array.prototype.map.call(document.querySelectorAll('script[type=\'text\/js-worker\']'), function (oScript) { return oScript.textContent; }),{type: 'text/javascript'}); + + // Creating a new document.worker property containing all our "text/js-worker" scripts. + document.worker = new Worker(window.URL.createObjectURL(blob)); + + document.worker.onmessage = function(oEvent) { + pageLog('Received: ' + oEvent.data); + }; + + // Start the worker. + window.onload = function() { document.worker.postMessage(''); }; +</script> +</head> +<body><div id="logDisplay"></div></body> +</html></pre> + +<p>The embedded worker is now nested into a new custom <code>document.worker</code> property.</p> + +<p>It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:</p> + +<pre class="brush: js">function fn2workerURL(fn) { + var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'}) + return URL.createObjectURL(blob) +}</pre> + +<h2 id="Exemplos_adicionais">Exemplos adicionais</h2> + +<p>This section provides further examples of how to use web workers.</p> + +<h3 id="Realizar_computações_em_segundo_plano">Realizar computações em segundo plano</h3> + +<p>Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.</p> + +<h4 id="O_código_de_JavaScript">O código de JavaScript</h4> + +<p>The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.</p> + +<pre class="brush: js">var results = []; + +function resultReceiver(event) { + results.push(parseInt(event.data)); + if (results.length == 2) { + postMessage(results[0] + results[1]); + } +} + +function errorReceiver(event) { + throw event.data; +} + +onmessage = function(event) { + var n = parseInt(event.data); + + if (n == 0 || n == 1) { + postMessage(n); + return; + } + + for (var i = 1; i <= 2; i++) { + var worker = new Worker('fibonacci.js'); + worker.onmessage = resultReceiver; + worker.onerror = errorReceiver; + worker.postMessage(n - i); + } + };</pre> + +<p>The worker sets the property <code>onmessage</code> to a function which will receive messages sent when the worker object's <code>postMessage()</code> is called (note that this differs from defining a global <em>variable</em> of that name, or defining a <em>function</em> with that name. <code>var onmessage</code> and <code>function onmessage</code> will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.</p> + +<h4 id="O_código_de_HTML">O código de HTML</h4> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta charset="UTF-8" /> + <title>Test threads fibonacci</title> + </head> + <body> + + <div id="result"></div> + + <script language="javascript"> + + var worker = new Worker('fibonacci.js'); + + worker.onmessage = function(event) { + document.getElementById('result').textContent = event.data; + dump('Got: ' + event.data + '\n'); + }; + + worker.onerror = function(error) { + dump('Worker error: ' + error.message + '\n'); + throw error; + }; + + worker.postMessage('5'); + + </script> + </body> +</html> +</pre> + +<p>The web page creates a <code>div</code> element with the ID <code>result</code> , which gets used to display the result, then spawns the worker. After spawning the worker, the <code>onmessage</code> handler is configured to display the results by setting the contents of the <code>div</code> element, and the <code>onerror</code> handler is set to <a href="/en-US/docs/Debugging_JavaScript#dump.28.29">dump</a> the error message.</p> + +<p>Finally, a message is sent to the worker to start it.</p> + +<p><a class="external" href="/samples/workers/fibonacci">Try this example</a>.</p> + +<h3 id="Executar_IO_da_Web_em_segundo_plano">Executar I/O da Web em segundo plano</h3> + +<p>You can find an example of this in the article <a class="internal" href="/en-US/docs/Using_workers_in_extensions">Using workers in extensions</a> .</p> + +<h3 id="Dividir_tarefas_entre_mútiplos_workers">Dividir tarefas entre mútiplos <em>workers</em></h3> + +<p>As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.</p> + +<h2 id="Outros_tipos_de_worker">Outros tipos de <em>worker</em></h2> + +<p>In addition to dedicated and shared web workers, there are other types of worker available:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorkers</a> essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.</li> + <li>Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to <a href="https://developer.mozilla.org/en/js-ctypes">js-ctypes</a> in your worker. See {{domxref("ChromeWorker")}} for more details.</li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API#Audio_Workers">Audio Workers</a> provide the ability for direct scripted audio processing to be done in a web worker context.</li> +</ul> + +<h2 id="Funções_e_interfaces_disponíveis_nos_workers">Funções e interfaces disponíveis nos <em>workers</em></h2> + +<p>You can use most standard JavaScript features inside a web worker, including:</p> + +<ul> + <li>{{domxref("Navigator")}}</li> + <li>{{domxref("XMLHttpRequest")}}</li> + <li>{{jsxref("Global_Objects/Array", "Array")}}, {{jsxref("Global_Objects/Date", "Date")}}, {{jsxref("Global_Objects/Math", "Math")}}, and {{jsxref("Global_Objects/String", "String")}}</li> + <li>{{domxref("WindowTimers.setTimeout")}} and {{domxref("WindowTimers.setInterval")}}</li> +</ul> + +<p>The main thing you <em>can't</em> do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.</p> + +<div class="note"> +<p><strong>Note</strong>: For a complete list of functions available to workers, see <a href="/en-US/docs/Web/Reference/Functions_and_classes_available_to_workers">Functions and interfaces available to workers</a>.</p> +</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10.0</td> + <td>10.6<sup>[1]</sup></td> + <td>4<sup>[2]</sup></td> + </tr> + <tr> + <td>Shared workers</td> + <td>4<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatNo}}</td> + <td>10.6</td> + <td>5<br> + {{CompatNo}} 6.1<sup>[4]</sup></td> + </tr> + <tr> + <td>Passing data using <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a></td> + <td>13</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>10.0</td> + <td>11.5</td> + <td>6</td> + </tr> + <tr> + <td>Passing data using <a class="external" href="http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#transferable-objects">transferable objects</a></td> + <td>17 {{property_prefix("webkit")}}<br> + 21</td> + <td>{{CompatGeckoDesktop(18)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>6</td> + </tr> + <tr> + <td>Global {{domxref("window.URL", "URL")}}</td> + <td>10<sup>[3]</sup><br> + 23</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>11</td> + <td>15</td> + <td>6<sup>[3]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>4<sup>[1]</sup></td> + <td>3.5</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5<sup>[1]</sup></td> + <td>5.1<sup>[2]</sup></td> + </tr> + <tr> + <td>Shared workers</td> + <td>{{CompatNo}}</td> + <td>4<sup>[1]</sup></td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a></td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using <a class="external" href="http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#transferable-objects">transferable objects</a></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>18</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Chrome and Opera give an error "<code>Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'.</code>" when you try to run a worker locally. It needs to be on a proper domain.</p> + +<p>[2] As of Safari 7.1.2, you can call <code>console.log</code> from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call <code>console.log</code> from inside a worker.</p> + +<p>[3] This feature is implemented prefixed as <code>webkitURL</code>.</p> + +<p>[4] Safari <a href="https://bugs.webkit.org/show_bug.cgi?id=116359">removed SharedWorker support</a>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>Interface de <em><code><a class="internal" href="/en-US/docs/Web/API/Worker">Worker</a></code></em></li> + <li>Interface de <em><code><a class="internal" href="/en-US/docs/Web/API/SharedWorker">SharedWorker</a></code></em></li> + <li><a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Funções disponíveis para os <em>workers</em></a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Conceitos avançados e exemplos</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none; font-size: 14px; line-height: 20px; margin-top: 22168px; margin-left: 26px; direction: ltr; text-align: left;">Further</div> + +<div id="SL_shadow_translator" style="display: none; top: 152px; left: 25px; box-shadow: rgb(186, 185, 181) 0px 0px 0px; width: 467px;"> +<div id="SL_planshet" style="background: rgb(239, 239, 239) none repeat scroll 0% 0%;"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none; left: 49px;"> </div> + +<div id="SL_Bproviders" style=""> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_OFF" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_OFF" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; cursor: not-allowed;" title="Se o idioma de origem é definido como 'Detectar idioma', esta função não está disponível."> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy_hand" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch" style="display: none;"> </div> + + <div class="SL_font_on" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style="font-size: 14px; line-height: 20px; direction: ltr; text-align: left;">Further</div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none;"> </div> + +<div id="SL_player2" style="display: none; height: 0px;"> </div> + +<div id="SL_alert100" style="display: none;">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(239, 239, 239) none repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block; left: 49px;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> |