From 74f1c3c85cf4f0ff1cc631d1320ed90c404c6ed7 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Sun, 11 Jul 2021 13:02:49 -0400 Subject: delete conflicting/orphaned docs in ru (#1426) --- .../api/canvas_api/a_basic_ray-caster/index.html | 51 --- .../web/api/crypto/getrandomvalues/index.html | 112 ------ .../web/api/document_object_model/index.html | 63 --- .../index.html | 26 -- .../index.html | 39 -- files/ru/conflicting/web/api/element/index.html | 46 --- .../index.html | 133 ------- .../api/eventtarget/addeventlistener/index.html | 10 - .../api/eventtarget/removeeventlistener/index.html | 93 ----- .../ru/conflicting/web/api/geolocation/index.html | 104 ----- .../api/htmlmediaelement/abort_event/index.html | 71 ---- files/ru/conflicting/web/api/index.html | 132 ------- files/ru/conflicting/web/api/node/index.html | 27 -- .../index.html | 30 -- files/ru/conflicting/web/api/push_api/index.html | 421 --------------------- .../web/api/svgaelement/target/index.html | 108 ------ .../conflicting/web/api/web_storage_api/index.html | 369 ------------------ files/ru/conflicting/web/api/webrtc_api/index.html | 36 -- .../signaling_and_video_calling/index.html | 352 ----------------- .../web/api/window/localstorage/index.html | 147 ------- .../web/api/windoworworkerglobalscope/index.html | 122 ------ .../index.html | 121 ------ .../conflicting/web/api/xmlhttprequest/index.html | 283 -------------- 23 files changed, 2896 deletions(-) delete mode 100644 files/ru/conflicting/web/api/canvas_api/a_basic_ray-caster/index.html delete mode 100644 files/ru/conflicting/web/api/crypto/getrandomvalues/index.html delete mode 100644 files/ru/conflicting/web/api/document_object_model/index.html delete mode 100644 files/ru/conflicting/web/api/document_object_model_5521049528397035462607d58539e0cc/index.html delete mode 100644 files/ru/conflicting/web/api/document_object_model_dd00a71ceceac547ab464128db6bd8ef/index.html delete mode 100644 files/ru/conflicting/web/api/element/index.html delete mode 100644 files/ru/conflicting/web/api/element_861159909c20acebf8e506c3bb0e2f7e/index.html delete mode 100644 files/ru/conflicting/web/api/eventtarget/addeventlistener/index.html delete mode 100644 files/ru/conflicting/web/api/eventtarget/removeeventlistener/index.html delete mode 100644 files/ru/conflicting/web/api/geolocation/index.html delete mode 100644 files/ru/conflicting/web/api/htmlmediaelement/abort_event/index.html delete mode 100644 files/ru/conflicting/web/api/index.html delete mode 100644 files/ru/conflicting/web/api/node/index.html delete mode 100644 files/ru/conflicting/web/api/node_378aed5ed6869e50853edbc988cf9556/index.html delete mode 100644 files/ru/conflicting/web/api/push_api/index.html delete mode 100644 files/ru/conflicting/web/api/svgaelement/target/index.html delete mode 100644 files/ru/conflicting/web/api/web_storage_api/index.html delete mode 100644 files/ru/conflicting/web/api/webrtc_api/index.html delete mode 100644 files/ru/conflicting/web/api/webrtc_api/signaling_and_video_calling/index.html delete mode 100644 files/ru/conflicting/web/api/window/localstorage/index.html delete mode 100644 files/ru/conflicting/web/api/windoworworkerglobalscope/index.html delete mode 100644 files/ru/conflicting/web/api/windoworworkerglobalscope_e2691f7ad05781a30c5fc5bb3b3f633a/index.html delete mode 100644 files/ru/conflicting/web/api/xmlhttprequest/index.html (limited to 'files/ru/conflicting/web/api') diff --git a/files/ru/conflicting/web/api/canvas_api/a_basic_ray-caster/index.html b/files/ru/conflicting/web/api/canvas_api/a_basic_ray-caster/index.html deleted file mode 100644 index b96f0a95a3..0000000000 --- a/files/ru/conflicting/web/api/canvas_api/a_basic_ray-caster/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: A Basic RayCaster -slug: conflicting/Web/API/Canvas_API/A_basic_ray-caster -tags: - - Canvas_examples -original_slug: A_Basic_RayCaster ---- -

 

- -

The raycaster in action

- -

View the live demo.

- -

Why?

- -

After realizing, to my delight, that the nifty <canvas> element I'd been reading about was not only soon to be supported in Firefox, but wasalready supported in the current version of Safari, I had to try a little experiment.

- -

The canvas overview and tutorial I found here at MDC are great, but nobody had written about animation yet, so I thought I'd try a port of a basic raycaster I'd worked on a while ago, and see what sort of performance we can expect from a javascript controlled pixel buffer.

- -

How?

- -

The basic idea is to use setInterval at some arbitrary delay that corresponds to a desired frame rate. After every interval an update function will repaint the canvas showing the current view. I know I could have started with a simpler example, but I'm sure the canvas tutorial will get to that, and I wanted to see if I could do this.

- -

So every update, the raycaster looks to see if you've pressed any keys lately, to conserve calculations by not casting if you're idle. If you have, then the canvas is cleared, the ground and sky are drawn, the camera position and / or orientation are updated and the rays are cast out. As the rays intersect walls, then they render a vertical sliver of canvas in the color of the wall they've hit, blended with a darker version of the color according to the distance to the wall. The height of the sliver is also modulated by the distance from the camera to the wall, and is drawn centered over the horizon line.

- -

The code I ended up with is a regurgitated amalgam of the raycaster chapters from an old André LaMotheTricks of the Game Programming Gurus book (ISBN: 0672305070), and a java raycaster I found online, filtered through my compulsion to rename everything so it makes sense to me, and all the tinkering that had to be done to make things work well.

- -

Results

- -

The canvas in Safari 2.0.1 performed suprisingly well. With the blockiness factor cranked up to render slivers 8 pixels wide, I can run a 320 x 240 window at 24 fps on my Apple mini. Firefox 1.5 Beta 1 is even faster; I can run 320 x 240 at 24 fps with 4 pixel slivers. Not exactly a new member of the ID software family, but pretty decent considering it's a fully interpreted environment, and I didn't have to worry about memory allocation or video modes or coding inner routines in assembler or anything. The code does attempt to be very efficient, using array look-ups of pre-computed values, but I'm no optimization guru, so things could probably be written faster.

- -

Also, it leaves a lot to be desired in terms of trying to be any sort of game engine—there are no wall textures, no sprites, no doors, not even any teleporters to get to another level. But I'm pretty confident all those things could be added given enough time. The canvas API supports pixel copying of images, so textures seem feasible. I'll leave that for another article, probably from another person. =)

- -

The RayCaster

- -

The nice people here have manually copied my files up so you can take a look, and for your hacking enjoyment I've posted the individual file contents as code listings (see below).

- -

So there you are, fire up Safari 1.3+ or Firefox 1.5+ or some other browser that supports the <canvas> element and enjoy!
-
- input.js | Level.js | Player.js | RayCaster.html | RayCaster.js | trace.css | trace.js

- -

See Also

- - - -

{{ languages( { "fr": "fr/Un_raycaster_basique", "ja": "ja/A_Basic_RayCaster", "pl": "pl/Prosty_RayCaster" } ) }}

diff --git a/files/ru/conflicting/web/api/crypto/getrandomvalues/index.html b/files/ru/conflicting/web/api/crypto/getrandomvalues/index.html deleted file mode 100644 index 0193cc0447..0000000000 --- a/files/ru/conflicting/web/api/crypto/getrandomvalues/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: RandomSource -slug: conflicting/Web/API/Crypto/getRandomValues -tags: - - API - - Interface - - NeedsTranslation - - RandomSource - - Reference - - TopicStub - - Web Crypto API -translation_of: Web/API/Crypto/getRandomValues -translation_of_original: Web/API/RandomSource -original_slug: Web/API/RandomSource ---- -

{{APIRef("Web Crypto API")}}

- -

RandomSource представляет собой источник криптографически безопасных случайных чисел. Он доступен через {{domxref("Crypto")}} объект глобального объекта: {{domxref("Window.crypto")}} на веб страницах, {{domxref("WorkerGlobalScope.crypto")}} для воркеров.

- -

RandomSource не является интерфейсом и объект этого типа не может быть создан.

- -

Свойства

- -

RandomSource не объявляет и не наследует никаких свойств.

- -
-
- -

Методы

- -
-
{{ domxref("RandomSource.getRandomValues()") }}
-
Наполняет {{ domxref("ArrayBufferView") }} криптографически безопасными случайными числовыми значениями.
-
- -

Спецификации

- - - - - - - - - - - - - - -
СпецификацияСтатусКоммент
{{SpecName('Web Crypto API', '#dfn-RandomSource')}}{{Spec2('Web Crypto API')}}Изначальное определение
- -

Совместимость с браузерами

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
ВозможностьChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка11.0 {{ webkitbug("22049") }}{{CompatGeckoDesktop(21)}} [1]11.015.03.1
-
- -
- - - - - - - - - - - - - - - - - - - - - -
ВозможностьAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{ CompatNo() }}23{{CompatGeckoMobile(21)}}{{ CompatNo() }}{{ CompatNo() }}6
-
- -

[1] Although the transparent RandomSource is only available since Firefox 26, the feature was available in Firefox 21.

- -

Смотрите также

- - diff --git a/files/ru/conflicting/web/api/document_object_model/index.html b/files/ru/conflicting/web/api/document_object_model/index.html deleted file mode 100644 index 1432597b41..0000000000 --- a/files/ru/conflicting/web/api/document_object_model/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: DOM -slug: conflicting/Web/API/Document_Object_Model -tags: - - DOM -translation_of: Web/API/Document_Object_Model -translation_of_original: DOM -original_slug: DOM ---- -
-

Объектная модель документа (DOM) — это API для HTML и XML документов. Она предоставляет структуру документа, что позволяет изменять его содержимое и внешний вид. По сути, она связывает веб-страницы со скриптами или языками программирования.

-
- - - - - - - -
-

Документация

-
-
- Справочная информация по Gecko DOM
-
- Объектная модель документа движка Gecko.
-
- Об объектной модели документа
-
- Краткое введение в DOM.
-
- Динамически изменяемый пользовательский интерфейс на XUL
-
- Основы управления XUL UI с помощью методов DOM.
-
- DOM и JavaScript
-
- Что такое DOM? Что такое JavaScript? Как мне использовать их совместно на моей веб-странице? Этот документ отвечает на эти и другие вопросы.
-
- Объектная модель документа Mozilla
-
- Более старая документация по DOM, размещённая на mozilla.org.
-
-

Посмотреть все...

-
-

Сообщество

-
    -
  • Форумы Mozilla... {{ DiscussionList("dev-tech-dom", "mozilla.dev.tech.dom") }}
  • -
-

Инструменты

- -

Посмотреть все...

- - -
-

 

diff --git a/files/ru/conflicting/web/api/document_object_model_5521049528397035462607d58539e0cc/index.html b/files/ru/conflicting/web/api/document_object_model_5521049528397035462607d58539e0cc/index.html deleted file mode 100644 index 7794d4e392..0000000000 --- a/files/ru/conflicting/web/api/document_object_model_5521049528397035462607d58539e0cc/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Об объектной модели документа -slug: conflicting/Web/API/Document_Object_Model_5521049528397035462607d58539e0cc -tags: - - DOM -translation_of: Web/API/Document_Object_Model -translation_of_original: DOM/About_the_Document_Object_Model -original_slug: Об_объектной_модели_документа ---- -

Что такое DOM?

- -

Document Object Model — это API для HTML и XML документов. Она предоставляет структурное представление документа, что позволяет изменять его содержимое и внешний вид. По сути, она связывает веб-страницы со скриптами или языками программирования.

- -

Все свойства, методы и события, доступные веб-разработчику для манипулирования и создания веб-страниц организованы в объекты (например, объект document, который представляет сам документ, объект table, который представляет элементы HTML-таблицы, и т.д.). Эти объекты доступны через скриптовые языки в большинстве современных браузеров.

- -

В основном DOM используется вместе с JavaScript. То есть код пишется на JavaScript, но он использует DOM для доступа к веб-странице и её элементам. Тем не менее, DOM создавался, чтобы независимо от конкретных языков программирования имелась возможность доступа к структурному представлению документа через один API. Несмотря на то, что на этом сайте мы заострим внимание на JavaScript, реализации DOM могут быть созданы для любого языка.

- -

World Wide Web Consortium установил стандарт для DOM, называемый W3C DOM. Сейчас, когда большинство браузеров поддерживают этот стандарт, появилась возможность создавать мощные кросс-браузерные приложения.

- -

Почему так важна поддержка DOM в Mozilla?

- -

"Динамический HTML" (DHTML) — это термин, под которым понимают совокупность HTML, CSS и скриптов, которые позволяют создавать анимированные веб-страницы. Поскольку Mozilla позиционирует свой продукт как "платформу для веб-приложений", поддержка DOM является очень важной и необходимой, чтобы Mozilla была достойной альтернативой другим браузерам.

- -

Ещё более важным фактом является то, что пользовательский интерфейс в Mozilla (а также в Firefox и Thunderbird) построен на XUL — языке разметки пользовательского интерфейса. Так что Mozilla использует DOM для изменения своего интерфейса.

- -

{{ languages( { "es": "es/Acerca_del_Modelo_de_Objetos_del_Documento", "fr": "fr/\u00c0_propos_du_Document_Object_Model", "ja": "ja/About_the_Document_Object_Model", "ko": "ko/About_the_Document_Object_Model", "pl": "pl/O_modelu_obiektowym_dokumentu", "zh-cn": "cn/\u5173\u4e8e\u6587\u6863\u5bf9\u8c61\u6a21\u578b" } ) }}

diff --git a/files/ru/conflicting/web/api/document_object_model_dd00a71ceceac547ab464128db6bd8ef/index.html b/files/ru/conflicting/web/api/document_object_model_dd00a71ceceac547ab464128db6bd8ef/index.html deleted file mode 100644 index 4d8706e804..0000000000 --- a/files/ru/conflicting/web/api/document_object_model_dd00a71ceceac547ab464128db6bd8ef/index.html +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: DOM developer guide -slug: conflicting/Web/API/Document_Object_Model_dd00a71ceceac547ab464128db6bd8ef -tags: - - API - - DOM - - Guide - - NeedsContent - - NeedsTranslation - - TopicStub -translation_of: Web/API/Document_Object_Model -translation_of_original: Web/Guide/API/DOM -original_slug: Web/Guide/API/DOM ---- -

{{draft}}

- -

Объектная модель документа - это API для документов HTML и XML. Она обеспечивает структурное представление документа, позволяя разработчику изменять его содержание и визуальное представление. По сути, она соединяет веб-страницы со скриптами или языками программирования.

- -

Все свойства, методы и события, доступные веб-разработчику для манипулирования и создания веб-страниц, организованы в объекты (например, объект документа, представляющий сам документ, объект таблицы, представляющий элемент таблицы HTML и т. Д.) , Эти объекты доступны через скриптовые языки в самых последних веб-браузерах.

- -

DOM чаще всего используется в сочетании с JavaScript. Тем не менее, DOM был разработан, чтобы быть независимым от какого-либо конкретного языка программирования, делая структурное представление документа доступным из единого, согласованного API. Хотя мы,на этом сайте, сосредоточены на JavaScript реализации DOM могут быть построены для любого языка.

- -

Консорциум World Wide Web устанавливает стандарт для DOM, называемый W3C DOM. Теперь, когда наиболее важные браузеры правильно его реализуют, следует включить мощные кросс-браузерные приложения.

- -

Почему так важен DOM?

- -

"Dynamic HTML" (DHTML) это термин, используемый некоторыми поставщиками для описания комбинации HTML, таблиц стилей и сценариев, позволяющих анимировать документы. Рабочая группа W3C DOM усердно работает над тем, чтобы согласовать совместимые и не зависящие от языка решения (см. также W3C FAQ).

- -

Поскольку Mozilla претендует на звание «Платформа веб-приложений», поддержка DOM является одной из наиболее востребованных функций и необходимой, если Mozilla хочет стать жизнеспособной альтернативой другим браузерам. Пользовательский интерфейс Mozilla (также Firefox и Thunderbird) построен с использованием XUL, используя DOM для управления собственным пользовательским  интерфейсом UI.

- -

More about the DOM

- -

{{LandingPageListSubpages}}

- - - -

«Динамический HTML» (DHTML) - это термин, используемый некоторыми поставщиками для описания комбинации HTML, таблиц стилей и сценариев, позволяющих анимировать документы. Рабочая группа W3C DOM усердно работает над тем, чтобы согласовать совместимые и не зависящие от языка решения (см. Также FAQ по W3C).

- -

Поскольку Mozilla претендует на звание «Платформа веб-приложений», поддержка DOM является одной из наиболее востребованных функций и необходимой, если Mozilla хочет стать жизнеспособной альтернативой другим браузерам. Пользовательский интерфейс Mozilla (также Firefox и Thunderbird) построен с использованием XUL, используя DOM для управления собственным пользовательским интерфейсом.

diff --git a/files/ru/conflicting/web/api/element/index.html b/files/ru/conflicting/web/api/element/index.html deleted file mode 100644 index 8656365064..0000000000 --- a/files/ru/conflicting/web/api/element/index.html +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Slotable -slug: conflicting/Web/API/Element -tags: - - миксины -translation_of: Web/API/Slottable -translation_of_original: Web/API/Slotable -original_slug: Web/API/Slotable ---- -

{{APIRef("Shadow DOM")}}

- -

Миксин Slotable определяет возможности, которые позволяют нодам становиться контентом элемента {{htmlelement("slot")}} — следующие возможности включены в  {{domxref("Element")}} и {{domxref("Text")}}.

- -

Свойства

- -
-
{{domxref("Slotable.assignedSlot")}} {{readonlyInline}}
-
Возвращает {{htmlelement("slot")}}, в который вставлена нода.
-
- -

Методы

- -

Нет.

- -

Спецификации

- - - - - - - - - - - - - - -
СпецификацияСтатусКомментарии
{{SpecName('DOM WHATWG','#slotable','Slotable')}}{{Spec2('DOM WHATWG')}}Первое определение.
- -

Поддержка браузерами

- - - -

{{Compat("api.Slotable")}}

diff --git a/files/ru/conflicting/web/api/element_861159909c20acebf8e506c3bb0e2f7e/index.html b/files/ru/conflicting/web/api/element_861159909c20acebf8e506c3bb0e2f7e/index.html deleted file mode 100644 index 64a1aab95a..0000000000 --- a/files/ru/conflicting/web/api/element_861159909c20acebf8e506c3bb0e2f7e/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: NonDocumentTypeChildNode -slug: conflicting/Web/API/Element_861159909c20acebf8e506c3bb0e2f7e -tags: - - API - - DOM - - Interface - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/API/NonDocumentTypeChildNode -original_slug: Web/API/NonDocumentTypeChildNode ---- -
{{APIRef("DOM")}}
- -

The NonDocumentTypeChildNode interface contains methods that are particular to {{domxref("Node")}} objects that can have a parent, but not suitable for {{domxref("DocumentType")}}.

- -

NonDocumentTypeChildNode is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, and {{domxref("CharacterData")}} objects.

- -

Properties

- -

There is no inherited property.

- -
-
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
-
Returns the {{domxref("Element")}} immediately prior to this node in its parent's children list, or null if there is no {{domxref("Element")}} in the list prior to this node.
-
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
-
Returns the {{domxref("Element")}} immediately following this node in its parent's children list, or null if there is no {{domxref("Element")}} in the list following this node.
-
- -

Methods

- -

There is neither inherited, nor specific method.

- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-childnode', 'NonDocumentTypeChildNode')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, and NonDocumentTypeChildNode. The previousElementSibling and nextElementSibling are now defined on the latter.
- The {{domxref("CharacterData")}} and {{domxref("Element")}} implemented the new interfaces.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
- -

Browser compatibility

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}})1.0{{CompatGeckoDesktop("1.9.1")}}9.010.04.0
Support (on {{domxref("CharacterData")}})1.0{{CompatGeckoDesktop("25.0")}} [1]9.010.04.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{ CompatVersionUnknown() }}{{CompatGeckoDesktop("1.9.1")}}{{ CompatVersionUnknown() }}10.0{{ CompatVersionUnknown() }}
Support (on {{domxref("CharacterData")}}){{ CompatVersionUnknown() }}{{CompatGeckoDesktop("25.0")}}{{ CompatVersionUnknown() }}10.0{{ CompatVersionUnknown() }}
-
- -

[1] Firefox 25 also added the two properties defined here on {{domxref("DocumentType")}}, this was removed in Firefox 28 due to compatibility problems, and led to the creation of this new pure interface.

- -

See also

- - diff --git a/files/ru/conflicting/web/api/eventtarget/addeventlistener/index.html b/files/ru/conflicting/web/api/eventtarget/addeventlistener/index.html deleted file mode 100644 index ce515d9e4f..0000000000 --- a/files/ru/conflicting/web/api/eventtarget/addeventlistener/index.html +++ /dev/null @@ -1,10 +0,0 @@ ---- -title: EventTarget.attachEvent() -slug: conflicting/Web/API/EventTarget/addEventListener -tags: - - Junk -translation_of: Web/API/EventTarget/addEventListener -translation_of_original: Web/API/EventTarget/attachEvent -original_slug: Web/API/EventTarget/attachEvent ---- -

{{DOMxRef("EventTarget.addEventListener","EventTarget.addEventListener()")}}

diff --git a/files/ru/conflicting/web/api/eventtarget/removeeventlistener/index.html b/files/ru/conflicting/web/api/eventtarget/removeeventlistener/index.html deleted file mode 100644 index 63c2b0c366..0000000000 --- a/files/ru/conflicting/web/api/eventtarget/removeeventlistener/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: EventTarget.detachEvent() -slug: conflicting/Web/API/EventTarget/removeEventListener -translation_of: Web/API/EventTarget/removeEventListener -translation_of_original: Web/API/EventTarget/detachEvent -original_slug: Web/API/EventTarget/detachEvent ---- -

{{APIRef("DOM Events")}}

- -

{{ Non-standard_header() }}

- -

Кратко

- -

Это проприетарная альтернатива методу {{domxref("EventTarget.removeEventListener()")}}  в Microsoft Internet Explorer.

- -

Синтаксис

- -
target.detachEvent(eventNameWithOn, callback)
-
- -
-
target
-
DOM элемент, для которого надо убрать обработчик.
-
eventNameWithOn
-
Название события, начинающийся на "on" (так если бы это был колбэк атрибут), чей обработчик должен быть убран. Например, вам следует использовать "onclick" для удаления обработчика для данного "click" события.
-
callback
-
Функция, которую стоит убрать.
-
- -

Спецификация

- -

Не является частью спецификации.

- -

Microsoft содержит описание на MSDN.

- -

Поддержка браузерами

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Базовая поддержка{{ CompatNo() }}{{ CompatNo() }}6 thru 10 [1]{{ CompatUnknown() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Базовая поддержка{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatNo() }}
-
- -

[1]: detachEvent() больше не поддерживается в IE11+. {{domxref("EventTarget.removeEventListener()")}} поддерживается в IE9+.

- -

Смотрите так-же

- - diff --git a/files/ru/conflicting/web/api/geolocation/index.html b/files/ru/conflicting/web/api/geolocation/index.html deleted file mode 100644 index 9a15927312..0000000000 --- a/files/ru/conflicting/web/api/geolocation/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: NavigatorGeolocation -slug: conflicting/Web/API/Geolocation -translation_of: Web/API/Geolocation -translation_of_original: Web/API/NavigatorGeolocation -original_slug: Web/API/NavigatorGeolocation ---- -
{{APIRef("Geolocation API")}}
- -

NavigatorGeolocation содержит метод, позволяющий объектам реализовывать его,, получая {{domxref("Geolocation")}} экземпляр объекта.

- -

Здесь нет объектов типа NavigatorGeolocation, но некоторые интерфейсы, например, {{domxref("Navigator")}} реализуют его.

- -

Свойства

- -

Интерфейс NavigatorGeolocation не наследует каких-либо свойств.

- -
-
{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}
-
Возвращает объект {{domxref("Geolocation")}} позволяющий получить доступ к местоположению устройства.
-
- -

Методы

- -

Интерфейс NavigatorGeolocation ни реализует, ни наследует  никаких методов.

- -

Спецификации

- - - - - - - - - - - - - - - - -
СпецификацияСтатусКомментарий
{{SpecName('Geolocation', '#navi-geo', 'NavigatorGeolocation')}}{{Spec2('Geolocation')}}Изначальное описание
- -

Совместимость с браузерами

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
СвойствоChromeFirefox (Gecko)Internet ExplorerOperaSafari
Базовая поддержка5{{CompatGeckoDesktop("1.9.1")}}910.60
- {{CompatNo}} 15.0
- 16.0
5
-
- -
- - - - - - - - - - - - - - - - - - - - - -
СвойствоAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Базовая поддержка{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown}}10.60{{CompatUnknown}}
-
- -

Смотрите также

- - diff --git a/files/ru/conflicting/web/api/htmlmediaelement/abort_event/index.html b/files/ru/conflicting/web/api/htmlmediaelement/abort_event/index.html deleted file mode 100644 index 22fadfb200..0000000000 --- a/files/ru/conflicting/web/api/htmlmediaelement/abort_event/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: abort -slug: conflicting/Web/API/HTMLMediaElement/abort_event -tags: - - Событие -translation_of: Web/API/HTMLMediaElement/abort_event -translation_of_original: Web/Events/abort -original_slug: Web/Events/abort ---- -

Событие "abort" вызывается когда загрузка какого-либо ресурса была прервана.

- -

Общая информация

- -
-
Спецификация
-
DOM L3
-
Интерфейс
-
{{domxref("UIEvent")}} если событие сгенерировано из пользовательского интерфейса, иначе {{domxref("Event")}}.
-
Всплывание
-
Нет
-
Отменяемость
-
Нет
-
Цель
-
{{domxref("window")}}, {{domxref("Element")}}
-
Действие по умолчанию
-
Нет
-
- -

Свойства

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
СвойствоТипОписание
target {{readonlyInline}}EventTargetЦель события (самый вышележащий элемент в DOM дереве).
type {{readonlyInline}}DOMStringТип события.
bubbles {{readonlyInline}}BooleanПоднимается ли событие вверх как принято или нет.
cancelable {{readonlyInline}}BooleanЯвляется ли событие отменяемым или нет?
view {{readonlyInline}}WindowProxydocument.defaultView (свойство window  объекта document)
detail {{readonlyInline}}long (float)0.
diff --git a/files/ru/conflicting/web/api/index.html b/files/ru/conflicting/web/api/index.html deleted file mode 100644 index 325f2ca52b..0000000000 --- a/files/ru/conflicting/web/api/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: WebAPI -slug: conflicting/Web/API -tags: - - API -translation_of: Web/API -translation_of_original: WebAPI -original_slug: Web/WebAPI ---- -

WebAPI is a term used to refer to a suite of device compatibility and access APIs that allow Web apps and content to access device hardware (such as battery status or the device vibration hardware), as well as access to data stored on the device (such as the calendar or contacts list). By adding these APIs, we hope to expand what the Web can do today to also include what only proprietary platforms were able to do in the past.

- -
-

Note: For a brief explanation of each badge, please see the packaged apps documentation.

-
- -

 

- -
-
-

Communication APIs

- -
-
Network Information API
-
Provides basic information about the current network connection, such as connection speed.
-
Bluetooth {{NonStandardBadge}}
-
The WebBluetooth API provides low-level access to the device's Bluetooth hardware.
-
Mobile Connection API {{NonStandardBadge}}
-
Exposes information about the device's cellular connectivity, such as signal strength, operator information, and so forth.
-
Network Stats API {{NonStandardBadge}}
-
Monitors data usage and exposes this data to privileged applications.
-
Telephony {{NonStandardBadge}}
-
Lets apps place and answer phone calls and use the built-in telephony user interface.
-
WebSMS {{NonStandardBadge}}
-
Lets apps send and receive SMS text messages, as well as to access and manage the messages stored on the device.
-
WiFi Information API {{NonStandardBadge}}
-
A privileged API which provides information about signal strength, the name of the current network, available WiFi networks, and so forth.
-
- -

Hardware access APIs

- -
-
Ambient Light Sensor API
-
Provides access to the ambient light sensor, which lets your app detect the ambient light level in the vicinity of the device.
-
Battery Status API
-
Provides information about the battery's charge level and whether or not the device is currently plugged in and charging.
-
Geolocation API
-
Provides information about the device's physical location.
-
Pointer Lock API
-
Lets apps lock access to the mouse and gain access to movement deltas rather than absolute coordinates; this is great for gaming.
-
Proximity API
-
Lets you detect proximity of the device to a nearby object, such as the user's face.
-
Device Orientation API
-
Provides notifications when the device's orientation changes.
-
Screen Orientation API
-
Provides notifications when the screen's orientation changes. You can also use this API to let your app indicate what orientation it prefers.
-
Vibration API
-
Lets apps control the device's vibration hardware for things such as haptic feedback in games. This is not intended for things such as notification vibrations. See the Alarm API for that.
-
Camera API {{NonStandardBadge}}
-
Allows apps to take photographs and/or record video using the device's built-in camera.
-
Power Management API {{NonStandardBadge}}
-
Lets apps turn on and off the screen, CPU, device power, and so forth. Also provides support for listening for and inspecting resource lock events.
-
- -

View All...

-
- -
-

Data management APIs

- -
-
FileHandle API {{NonStandardBadge}}
-
Provides support for writable files with locking support.
-
IndexedDB
-
Client-side storage of structured data with support for high-performance searches.
-
Settings API {{NonStandardBadge}}
-
Lets apps examine and change system-wide configuration options that are permanently stored on the device.
-
- -

Other APIs

- -
-
Alarm API
-
Lets apps schedule notifications. Also provides support for automatically launching an app at a specific time.
-
Simple Push API
-
Lets the platform send notification messages to specific applications.
-
Push API
-
Gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.
-
Web Notifications
-
Lets applications send notifications displayed at the system level.
-
Apps API {{NonStandardBadge}}
-
The Open WebApps API provides support for installing and managing Web apps. In addition, support is provided to let apps determine payment information.
-
Web Activities {{NonStandardBadge}}
-
Lets an app delegate an activity to another app; for example, an app might ask another app to select (or create) and return a photo. Typically the user is able to configure what apps are used for which activities.
-
WebPayment API {{NonStandardBadge}}
-
Lets Web content initiate payments and refunds for virtual goods.
-
Browser API {{NonStandardBadge}}
-
Provides support for building a Web browser completely using Web technologies (in essence, a browser within a browser).
-
- -
-
Idle API
-
Lets apps receive notifications when the user is not actively using the device.
-
Permissions API {{NonStandardBadge}}
-
Manages app permissions in a centralized location. Used by the Settings app.
-
Time/Clock API {{NonStandardBadge}}
-
Provides support for setting the current time. The time zone is set using the Settings API.
-
- -

WebAPI community

- -

If you need help with these APIs, there are several ways you can talk to other developers making use of them.

- -
    -
  • Consult the WebAPI forum: {{DiscussionList("dev-webapi", "mozilla.dev.webapi")}}
  • -
  • Visit the WebAPI IRC channel: #webapi
  • -
- -

Don't forget about the netiquette...

- - - - -
-
- -

 

- -

 

diff --git a/files/ru/conflicting/web/api/node/index.html b/files/ru/conflicting/web/api/node/index.html deleted file mode 100644 index 867810d345..0000000000 --- a/files/ru/conflicting/web/api/node/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Node.baseURIObject -slug: conflicting/Web/API/Node -translation_of: Web/API/Node -translation_of_original: Web/API/Node/baseURIObject -original_slug: Web/API/Node/baseURIObject ---- -
{{APIRef("DOM")}} {{Non-standard_header}}
- -

Свойство Node.baseURIObject возвращает {{Interface("nsIURI")}} представляющий базовый URL узла (обычно документ или элемент). Это похоже на {{domxref("Node.baseURI")}}, за исключением того, что возвращает nsIURI вместо строки.

- -

Это свойство существует на всех узлах (HTML, XUL, SVG, MathML, и т.д.), но только если скрипт пытается использовать его имея привилегии UniversalXPConnect.

- -

Смотрите {{domxref("Node.baseURI")}} для уточнения деталей что такое базовый URL.

- -

Синтаксис

- -
uriObj = node.baseURIObject
-
- -

Примечания

- -

Это свойство только для чтения; попытка записать информацию в него, будет сбрасывать исключения. Кроме того, это свойство может быть доступно только для привилегированного кода.

- -

Спецификация

- -

Нет какой-либо спецификации.

diff --git a/files/ru/conflicting/web/api/node_378aed5ed6869e50853edbc988cf9556/index.html b/files/ru/conflicting/web/api/node_378aed5ed6869e50853edbc988cf9556/index.html deleted file mode 100644 index 8de371b4cf..0000000000 --- a/files/ru/conflicting/web/api/node_378aed5ed6869e50853edbc988cf9556/index.html +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Node.nodePrincipal -slug: conflicting/Web/API/Node_378aed5ed6869e50853edbc988cf9556 -translation_of: Web/API/Node -translation_of_original: Web/API/Node/nodePrincipal -original_slug: Web/API/Node/nodePrincipal ---- -
-
{{APIRef("DOM")}}
-{{Non-standard_header}} - -

Свойство Node.nodePrincipal только для чтения, возвращающее объект {{Interface("nsIPrincipal")}}, представляющий текущий контекст безопасности узла.

- -

{{Note("Это свойство существует во всех узлах (HTML, XUL, SVG, MathML, и т.д.), но только если скрипт пытается использовать chrome привилегии.")}}

- -

Синтаксис

- -
principalObj = element.nodePrincipal
-
- -

Примечания

- -

Это свойство только для чтения; пытаясь вводить информацию в него, будет сбрасывать исключение.Кроме того, это свойство может быть доступно только для привилегированного кода.

- -

Спецификация

- -

Нет никакой спецификации.

-
- -

 

diff --git a/files/ru/conflicting/web/api/push_api/index.html b/files/ru/conflicting/web/api/push_api/index.html deleted file mode 100644 index b97028f3b5..0000000000 --- a/files/ru/conflicting/web/api/push_api/index.html +++ /dev/null @@ -1,421 +0,0 @@ ---- -title: Использование Push API -slug: conflicting/Web/API/Push_API -translation_of: Web/API/Push_API -translation_of_original: Web/API/Push_API/Using_the_Push_API -original_slug: Web/API/Push_API/Using_the_Push_API ---- -

W3C Push API предоставляет некоторую захватывающую новую функциональность для разработчиков для использования в web-приложениях: эта статья предлагает вводную информацию о том, как настроить Push-уведомления и управлять ими, с помощью простого демо.

- -

Возможность посылать сообщения или уведомления от сервера клиенту в любое время — независимо от того, активно приложение или нет — было прерогативой нативных приложений некоторое время, и наконец пришло в Web! Поддерживается большинства возможностей Push сейчас возможна в браузерах Firefox 43+ и Chrome 42+ на настольных компьютерах, мобильные платформы, возможно, скоро присоединятся. {{domxref("PushMessageData")}} на данный момент экспериментально поддерживаются только в Firefox Nightly (44+), и реализация может меняться.

- -
-

Примечание: Ранние версии Firefox OS использовали проприетарную версию этого API вызывая Simple Push. Считается устаревшим по стандартам Push API.

-
- -

Демо: основы простого сервера чат-приложения

- -

Демо, которые мы создали, представляет начальное описание простого чат-приложения. Оно представляет собой форму, в которую вводятся данные, и кнопку для подписки на push-сообщения . Как только кнопка будет нажата, вы подпишитесь на push-сообщения, ваши данные будут записаны на сервере, а отправленное push-сообщение сообщит всем текущим подписчикам, что кто-то подписался.

- -

На данном этапе, имя нового подписчика появится в списке подписчиков, вместе с текстовым полем и кнопкой рассылки, чтобы позволить подписчику отправить сообщение.

- -

- -

Чтобы запустить демо, следуйте инструкциям на странице push-api-demo README. Заметьте, что серверная компонента всё ещё нуждается в небольшой доработке для запуска в Chrome и в общем запускается более разумным путём. Но аспекты Push всё ещё могут быть полностью понятны; мы углубимся в это после того, как просмотрим технологии в процессе.

- -

Обзор технологии

- -

Эта секция предоставляет описание того, какие технологии участвуют в примере.

- -

Web Push-сообщения это часть семейства технологий сервис воркеров; в первую очередь, для получения push-сообщений сервис воркер должен быть активирован на странице. Сервис воркер получает push-сообщения, и затем вы сами решаете, как уведомить об этом страницу. Вы можете:

- - - -

Обычно необходима комбинация этих двух решений; демо внизу включает пример обоих.

- -
-

Примечание: вам необходим некоторый код, запущенный на сервере, для управления конечной точкой/шифрованием данных и отправки запросов push-сообщений. В нашем демо мы собрали на скорую руку сервер, используя NodeJS.

-
- -

Сервис воркер так же должен подписаться на сервис push-сообщений. Каждой сессии предоставляется собственная уникальная конечная точка, когда она подписывается на сервис push-сообщений. Эта конечная точка получается из свойства  ({{domxref("PushSubscription.endpoint")}}) объекта подписчика. Она может быть отправлена серверу и использоваться для пересылки сообщений активному сервис воркеру сессии. Каждый браузер имеет свой собственный сервер push-сообщений для  управления отправкой push-сообщений.

- -

Шифрование

- -
-

Примечание: Для интерактивного краткого обзора, попробуйте JR Conlin's Web Push Data Encryption Test Page.

-
- -

Для отправки данных с помощью push-сообщений необходимо шифрование. Для этого необходим публичный ключ, созданный с использованием метода  {{domxref("PushSubscription.getKey()")}}, который основывается на некотором комплексе механизмов шифрования, которые выполняются на стороне сервера; читайте Message Encryption for Web Push. Со временем появятся библиотеки для управления генерацией ключей и шифрованием/дешифрованием push-сообщений; для этого демо мы используем Marco Castelluccio's NodeJS web-push library.

- -
-

Примечание: Есть так же другая библиотека для управления шифрованием с помощью Node и Python, смотри encrypted-content-encoding.

-
- -

Обобщение рабочего процесса Push

- -

Общие сведения ниже это то, что необходимо для реализации push-сообщений. Вы можете найти больше информации о некоторых частях демо в последующих частях.

- -
    -
  1. Запрос на разрешение web-уведомлений или что-то другое, что вы используете и для чего необходимо разрешение.
  2. -
  3. Регистрация сервис воркера для контроля над страницей с помощью вызова {{domxref("ServiceWorkerContainer.register()")}}.
  4. -
  5. Подписка на сервис push-уведомлений с помощью {{domxref("PushManager.subscribe()")}}.
  6. -
  7. Запрашивание конечной точки, соответствующей подписчику, и генерация публичного ключа клиента ({{domxref("PushSubscription.endpoint")}} и {{domxref("PushSubscription.getKey()")}}. Заметьте, что getKey() на данный момент экспериментальная технология и доступна только в Firefox.)
  8. -
  9. Отправка данных на сервер, чтобы тот мог присылать push-сообщения, когда необходимо. Это демо использует {{domxref("XMLHttpRequest")}}, но вы можете использовать Fetch.
  10. -
  11. Если вы используете Channel Messaging API для связи с сервис воркером, установите новый канал связи ({{domxref("MessageChannel.MessageChannel()")}}) и отправьте port2 сервис воркеру с помощью вызова {{domxref("Worker.postMessage()")}} для того, чтобы открыть канал связи. Вы так же должны настроить обработчик ответов на сообщения, которые будут отправляться обратно с сервис воркера.
  12. -
  13. На стороне сервера сохраните конечную точку и все остальные необходимые данные, чтобы они были доступны, когда будет необходимо отправить push-сообщение добавленному подписчику (мы используем простой текстовый файл, но вы можете использовать базу данных или все что угодно на ваш вкус). В приложении на продакшене убедитесь, что скрываете эти данные, так что злоумышленники не смогут украсть конечную точку и разослать спам подписчикам в push-сообщениях.
  14. -
  15. Для отправки push-сообщений необходимо отослать HTTP POST конечному URL. Запрос должен включать TTL заголовок, который ограничивает время пребывания сообщения в очереди, если пользователь не в сети. Для добавления полезной информации в запросе, необходимо зашифровать её (что включает публичный ключ клиента). В нашем примере мы используем web-push модуль, который управляет всей тяжёлой работой.
  16. -
  17. Поверх в сервис воркере настройте обработчик событий push для ответов на полученные push-сообщения. -
      -
    1. Если вы хотите отвечать отправкой сообщения канала обратно основному контексту (смотри шаг 6), необходимо сначала получить ссылку на port2, который был отправлен контексту сервис воркера ({{domxref("MessagePort")}}). Это доступно в объекте  {{domxref("MessageEvent")}}, передаваемого обработчику onmessage ({{domxref("ServiceWorkerGlobalScope.onmessage")}}). Конкретнее, он находится в свойстве ports, индекс 0. Когда это сделано, вы можете отправить сообщение обратно port1, используя {{domxref("MessagePort.postMessage()")}}.
    2. -
    3. Если вы хотите ответить запуском системного уведомления, вы можете сделать это, вызвав {{domxref("ServiceWorkerRegistration.showNotification()")}}. Заметьте, что в нашем коде мы вызываем его внутри метода {{domxref("ExtendableEvent.waitUntil()")}} — это продлевает время жизни события до момента запуска уведомления и гарантирует, что метод showNotification будет завершён полностью.
    4. -
    -
  18. -
- -

Сборка демо

- -

Давайте пройдёмся по коду для демо, чтобы понять, как все работает.

- -

HTML и CSS

- -

Нет ничего примечательного в HTML и CSS демо; HTML содержит простую форму для ввода данных для входа в чат, кнопку для подписки на push-уведомления и двух списков, в которых перечислены подписчики и сообщения чата. После подписки появляются дополнительные средства для того, чтобы пользователь мог ввести сообщение в чат.

- -

CSS был оставлен очень минимальным, чтобы не отвлекать от объяснения того, как функционируют Push API.

- -

Основной файл JavaScript

- -

 JavaScript очевидно намного более существенный. Давайте взглянем на основной файл JavaScript.

- -

Переменные и начальные настройки

- -

Для начала определим некоторые переменные, которые будем использовать в нашем приложении:

- -
var isPushEnabled = false;
-var useNotifications = false;
-
-var subBtn = document.querySelector('.subscribe');
-var sendBtn;
-var sendInput;
-
-var controlsBlock = document.querySelector('.controls');
-var subscribersList = document.querySelector('.subscribers ul');
-var messagesList = document.querySelector('.messages ul');
-
-var nameForm = document.querySelector('#form');
-var nameInput = document.querySelector('#name-input');
-nameForm.onsubmit = function(e) {
-  e.preventDefault()
-};
-nameInput.value = 'Bob';
- -

Сначала нам необходимо создать две булевы переменные, для того чтобы отслеживать подписку на push-сообщения и подтверждение разрешения на рассылку уведомлений.

- -

Далее, мы перехватываем ссылку на {{htmlelement("button")}} подписки/отписки и задаём переменные для сохранения ссылок на наши кнопку отправки сообщения/ввода (который создастся только после успешной подписки).
-
- Следующие переменные перехватывают ссылки на три основные {{htmlelement("div")}} элемента, так что мы можем включить в них элементы (к примеру, когда появится кнопка Отправки Сообщения Чата или сообщение появится в списке сообщений).

- -

Наконец, мы берем ссылки на нашу форму выбора имени и элемент {{htmlelement("input")}}, присваиваем входу значение по умолчанию и используем preventDefault(), чтобы остановить отправку формы, которая будет отправлена нажатием кнопки return.

- -

Далее мы запрашиваем разрешение на отправку веб-уведомлений, используя {{domxref("Notification.requestPermission","requestPermission()")}}:

- -
Notification.requestPermission();
- -

Now we run a section of code when onload is fired, to start up the process of inialising the app when it is first loaded. First of all we add a click event listener to the subscribe/unsubscribe button that runs our unsubscribe() function if we are already subscribed (isPushEnabled is true), and subscribe() otherwise:

- -
window.addEventListener('load', function() {
-  subBtn.addEventListener('click', function() {
-    if (isPushEnabled) {
-      unsubscribe();
-    } else {
-      subscribe();
-    }
-  });
- -

Next we check to see if service workers are supported. If so, we register a service worker using {{domxref("ServiceWorkerContainer.register()")}}, and run our initialiseState() function. If not, we deliver an error message to the console.

- -
  // Check that service workers are supported, if so, progressively
-  // enhance and add push messaging support, otherwise continue without it.
-  if ('serviceWorker' in navigator) {
-    navigator.serviceWorker.register('sw.js').then(function(reg) {
-      if(reg.installing) {
-        console.log('Service worker installing');
-      } else if(reg.waiting) {
-        console.log('Service worker installed');
-      } else if(reg.active) {
-        console.log('Service worker active');
-      }
-
-      initialiseState(reg);
-    });
-  } else {
-    console.log('Service workers aren\'t supported in this browser.');
-  }
-});
-
- -

The next thing in the source code is the initialiseState() function — for the full commented code, look at the initialiseState() source on Github (we are not repeating it here for brevity's sake.)

- -

initialiseState() first checks whether notifications are supported on service workers, then sets the useNotifications variable to true if so. Next, it checks whether said notifications are permitted by the user, and if push messages are supported, and reacts accordingly to each.

- -

Finally, it uses {{domxref("ServiceWorkerContainer.ready()")}} to wait until the service worker is active and ready to start doing things. Once its promise resolves, we retrieve our subscription to push messaging using the {{domxref("ServiceWorkerRegistration.pushManager")}} property, which returns a {{domxref("PushManager")}} object that we then call {{domxref("PushManager.getSubscription()")}} on. Once this second inner promise resolves, we enable the subscribe/unsubscribe button (subBtn.disabled = false;), and check that we have a subscription object to work with.

- -

If we do, then we are already subscribed. This is possible when the app is not open in the browser; the service worker can still be active in the background. If we're subscribed, we update the UI to show that we are subscribed by updating the button label, then we set isPushEnabled to true, grab the subscription endpoint from {{domxref("PushSubscription.endpoint")}}, generate a public key using {{domxref("PushSubscription.getKey()")}}, and run our updateStatus() function, which as you'll see later communicates with the server.

- -

As an added bonus, we set up a new {{domxref("MessageChannel")}} using the {{domxref("MessageChannel.MessageChannel()")}} constructor, grab a reference to the active service worker using {{domxref("ServiceworkerRegistration.active")}}, then set up a channel betweeen the main browser context and the service worker context using {{domxref("Worker.postMessage()")}}. The browser context receives messages on {{domxref("MessageChannel.port1")}}; whenever that happens, we run the handleChannelMessage() function to decide what to do with that data (see the {{anch("Handling channel messages sent from the service worker")}} section).

- -

Subscribing and unsubscribing

- -

Let's now turn our attention to the subscribe() and unsubscribe() functions used to subscribe/unsubscribe to the push notification service.

- -

In the case of subscription, we again check that our service worker is active and ready by calling {{domxref("ServiceWorkerContainer.ready()")}}. When the promise resolves, we subscribe to the service using {{domxref("PushManager.subscribe()")}}. If the subscription is successful, we get a {{domxref("PushSubscription")}} object, extract the subscription endpoint from this and generate a public key (again, {{domxref("PushSubscription.endpoint")}} and {{domxref("PushSubscription.getKey()")}}), and pass them to our updateStatus() function along with the update type (subscribe) to send the necessary details to the server.

- -

We also make the necessary updates to the app state (set isPushEnabled to true) and UI (enable the subscribe/unsubscribe button and set its label text to show that the next time it is pressed it will unsubscribe.)

- -

The unsubscribe() function is pretty similar in structure, but it basically does the opposite; the most notable difference is that it gets the current subscription using {{domxref("PushManager.getSubscription()")}}, and when that promise resolves it unsubscribes using {{domxref("PushSubscription.unsubscribe()")}}.

- -

Appropriate error handling is also provided in both functions.  

- -

We only show the subscribe() code below, for brevity; see the full subscribe/unsubscribe code on Github.

- -
function subscribe() {
-  // Disable the button so it can't be changed while
-  // we process the permission request
-
-  subBtn.disabled = true;
-
-  navigator.serviceWorker.ready.then(function(reg) {
-    reg.pushManager.subscribe({userVisibleOnly: true})
-      .then(function(subscription) {
-        // The subscription was successful
-        isPushEnabled = true;
-        subBtn.textContent = 'Unsubscribe from Push Messaging';
-        subBtn.disabled = false;
-
-        // Update status to subscribe current user on server, and to let
-        // other users know this user has subscribed
-        var endpoint = subscription.endpoint;
-        var key = subscription.getKey('p256dh');
-        updateStatus(endpoint,key,'subscribe');
-      })
-      .catch(function(e) {
-        if (Notification.permission === 'denied') {
-          // The user denied the notification permission which
-          // means we failed to subscribe and the user will need
-          // to manually change the notification permission to
-          // subscribe to push messages
-          console.log('Permission for Notifications was denied');
-
-        } else {
-          // A problem occurred with the subscription, this can
-          // often be down to an issue or lack of the gcm_sender_id
-          // and / or gcm_user_visible_only
-          console.log('Unable to subscribe to push.', e);
-          subBtn.disabled = false;
-          subBtn.textContent = 'Subscribe to Push Messaging';
-        }
-      });
-  });
-}
- -

Updating the status in the app and server

- -

The next function in our main JavaScript is updateStatus(), which updates the UI for sending chat messages when subscribing/unsubscribing and sends a request to update this information on the server.

- -

The function does one of three different things, depending on the value of the statusType parameter passed into it:

- - - -

Again, we have not included the entire function listing for brevity. Examine the full updateStatus() code on Github.

- -

Handling channel messages sent from the service worker

- -

As mentioned earlier, when a channel message is received from the service worker, our handleChannelMessage() function is called to handle it. This is done by our handler for the {{event("message")}} event, {{domxref("channel.port1.onmessage")}}:

- -
channel.port1.onmessage = function(e) {
-  handleChannelMessage(e.data);
-}
- -

This occurs when the service worker sends a channel message over.

- -

The handleChannelMessage() function looks like this:

- -
function handleChannelMessage(data) {
-  if(data.action === 'subscribe' || data.action === 'init') {
-    var listItem = document.createElement('li');
-    listItem.textContent = data.name;
-    subscribersList.appendChild(listItem);
-  } else if(data.action === 'unsubscribe') {
-    for(i = 0; i < subscribersList.children.length; i++) {
-      if(subscribersList.children[i].textContent === data.name) {
-        subscribersList.children[i].parentNode.removeChild(subscribersList.children[i]);
-      }
-    }
-    nameInput.disabled = false;
-  } else if(data.action === 'chatMsg') {
-    var listItem = document.createElement('li');
-    listItem.textContent = data.name + ": " + data.msg;
-    messagesList.appendChild(listItem);
-    sendInput.value = '';
-  }
-}
- -

What happens here depends on what the action property on the data object is set to:

- - - -
-

Note: We have to pass the data back to the main context before we do DOM updates because service workers don't have access to the DOM. You should be aware of the limitations of service workers before attemping to ue them. Read Using Service Workers for more details.

-
- -

Sending chat messages

- -

When the Send Chat Message button is clicked, the content of the associated text field is sent as a chat message. This is handled by the sendChatMessage() function (again, not shown in full for brevity). This works in a similar way to the different parts of the updateStatus() function (see {{anch("Updating the status in the app and server")}}) — we retrieve an endpoint and public key via a {{domxref("PushSubscription")}} object, which is itself retrieved via {{domxref("ServiceWorkerContainer.ready()")}} and {{domxref("PushManager.subscribe()")}}. These are sent to the server via {{domxref("XMLHttpRequest")}} in a message object, along with the name of the subscribed user, the chat message to send, and a statusType of chatMsg.

- -

The server

- -

As mentioned above, we need a server-side component in our app, to handle storing subscription details, and send out push messages when updates occur. We've hacked together a quick-and-dirty server using NodeJS (server.js), which handles the XHR requests sent by our client-side JavaScript code.

- -

It uses a text file (endpoint.txt) to store subscription details; this file starts out empty. There are four different types of request, marked by the statusType property of the object sent over in the request; these are the same as those understood client-side, and perform the required server actions for that same situation. Here's what each means in the context of the server:

- - - -

A couple more things to note:

- - - -

The service worker

- -

Now let's have a look at the service worker code (sw.js), which responds to the push messages, represented by {{Event("push")}} events. These are handled on the service worker's scope by the ({{domxref("ServiceWorkerGlobalScope.onpush")}}) event handler; its job is to work out what to do in response to each received message. We first convert the received message back into an object by calling {{domxref("PushMessageData.json()")}}. Next, we check what type of push message it is, by looking at the object's action property:

- - - -
self.addEventListener('push', function(event) {
-  var obj = event.data.json();
-
-  if(obj.action === 'subscribe' || obj.action === 'unsubscribe') {
-    fireNotification(obj, event);
-    port.postMessage(obj);
-  } else if(obj.action === 'init' || obj.action === 'chatMsg') {
-    port.postMessage(obj);
-  }
-});
- -

Next, let's look at the fireNotification() function (which is blissfully pretty simple).

- -
function fireNotification(obj, event) {
-  var title = 'Subscription change';
-  var body = obj.name + ' has ' + obj.action + 'd.';
-  var icon = 'push-icon.png';
-  var tag = 'push';
-
-  event.waitUntil(self.registration.showNotification(title, {
-    body: body,
-    icon: icon,
-    tag: tag
-  }));
-}
- -

Here we assemble the assets needed by the notification box: the title, body, and icon. Then we send a notification via the {{domxref("ServiceWorkerRegistration.showNotification()")}} method, providing that information as well as the tag "push", which we can use to identify this notification among any other notifications we might be using. When the notification is successfully sent, it manifests as a system notification dialog on the users computers/devices in whatever style system notifications look like on those systems (the following image shows a Mac OSX system notification.)

- -

- -

Note that we do this from inside an {{domxref("ExtendableEvent.waitUntil()")}} method; this is to make sure the service worker remains active until the notification has been sent. waitUntil() will extend the life cycle of the service worker until everything inside this method has completed.

- -
-

Note: Web notifications from service workers were introduced around Firefox version 42, but are likely to be removed again while the surrounding functionality (such as Clients.openWindow()) is properly implemented (see {{bug(1203324)}} for more details.)

-
- -

Handling premature subscription expiration

- -

Sometimes push subscriptions expire prematurely, without {{domxref("PushSubscription.unsubscribe()")}} being called. This can happen when the server gets overloaded, or if you are offline for a long time, for example.  This is highly server-dependent, so the exact behavior is difficult to predict. In any case, you can handle this problem by watching for the {{Event("pushsubscriptionchange")}} event, which you can listen for by providing a {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} event handler; this event is fired only in this specific case.

- -
self.addEventListener('pushsubscriptionchange', function() {
-  // do something, usually resubscribe to push and
-  // send the new subscription details back to the
-  // server via XHR or Fetch
-});
- -

Note that we don't cover this case in our demo, as a subscription ending is not a big deal for a simple chat server. But for a more complex example you'd probably want to resubscribe the user.

- -

Extra steps for Chrome support

- -

To get the app working on Chrome, we need a few extra steps, as Chrome currently relies on Google's Cloud Messaging service to work.

- -

Setting up Google Cloud Messaging

- -

To get this set up, follow these steps:

- -
    -
  1. Navigate to the Google Developers Console  and set up a new project.
  2. -
  3. Go to your project's homepage (ours is at https://console.developers.google.com/project/push-project-978, for example), then -
      -
    1. Select the Enable Google APIs for use in your apps option.
    2. -
    3. In the next screen, click Cloud Messaging for Android under the Mobile APIs section.
    4. -
    5. Click the Enable API button.
    6. -
    -
  4. -
  5. Now you need to make a note of your project number and API key because you'll need them later. To find them: -
      -
    1. Project number: click Home on the left; the project number is clearly marked at the top of your project's home page.
    2. -
    3. API key: click Credentials on the left hand menu; the API key can be found on that screen.
    4. -
    -
  6. -
- -

manifest.json

- -

You need to include a Google app-style manifest.json file in your app, which references the project number you made a note of earlier in the gcm_sender_id parameter. Here is our simple example manifest.json:

- -
{
-  "name": "Push Demo",
-  "short_name": "Push Demo",
-  "icons": [{
-        "src": "push-icon.png",
-        "sizes": "111x111",
-        "type": "image/png"
-      }],
-  "start_url": "/index.html",
-  "display": "standalone",
-  "gcm_sender_id": "224273183921"
-}
- -

You also need to reference your manifest using a {{HTMLElement("link")}} element in your HTML:

- -
<link rel="manifest" href="manifest.json">
- -

userVisibleOnly

- -

Chrome requires you to set the userVisibleOnly parameter to true when subscribing to the push service, which indicates that we are promising to show a notification whenever a push is received. This can be seen in action in our subscribe() function.

- -

See also

- - - -
-

Note: Some of the client-side code in our Push demo is heavily influenced by Matt Gaunt's excellent examples in Push Notifications on the Open Web. Thanks for the awesome work, Matt!

-
diff --git a/files/ru/conflicting/web/api/svgaelement/target/index.html b/files/ru/conflicting/web/api/svgaelement/target/index.html deleted file mode 100644 index 376099e1f3..0000000000 --- a/files/ru/conflicting/web/api/svgaelement/target/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: SVGAElement.target -slug: conflicting/Web/API/SVGAElement/target -translation_of: Web/API/SVGAElement/target -translation_of_original: Web/API/SVGAElement/SVGAlement.target -original_slug: Web/API/SVGAElement/SVGAlement.target ---- -

{{APIRef("SVGAElement")}}

- -

 

- -

Свойство SVGAElement.target для чтения только {{domxref ("SVGAElement")}} возвращает объект {{domxref ("SVGAnimatedString")}}, который указывает часть целевого окна, фрейма, панель, в которую открывается при активации ссылки.

- -

Это свойство используется, когда существует множество возможных целей для конечного ресурса, например, когда родительский документ является документом HTML или HTML-документом mlti-frame.

- -

 

- -

Синтаксис

- -
myLink.target = 'value';
- -

Стоимость

- -

{{Domxref ("SVGAnimatedString")}}, указывающий конечную цель ресурса, которая открывает документ при активации ссылки.

- -

Значения для {{domxref ("target")}} можно увидеть here

- -

Пример

- -

Код  взят из "SVGAElement example code"

- -
...
-var linkRef = document.querySelector('a');
-linkRef.target ='_blank';
-...
- -

Характеристики

- - - - - - - - - - - - - - -
СпецификацияСтатусКомментарий
{{SpecName('SVG1.1', 'text.html#InterfaceSVGAElement', 'target')}}{{Spec2('SVG1.1')}} 
- -

Совместимость с браузером

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
-
- -

Смотрите также

- - diff --git a/files/ru/conflicting/web/api/web_storage_api/index.html b/files/ru/conflicting/web/api/web_storage_api/index.html deleted file mode 100644 index 80b1e15366..0000000000 --- a/files/ru/conflicting/web/api/web_storage_api/index.html +++ /dev/null @@ -1,369 +0,0 @@ ---- -title: DOM Storage guide -slug: conflicting/Web/API/Web_Storage_API -translation_of: Web/API/Web_Storage_API -translation_of_original: Web/Guide/API/DOM/Storage -original_slug: Web/Guide/API/DOM/Storage ---- -

 

- -

DOM хранилище (DOM Storage) - это название для набора инструментов, относящихся к хранилищам, впервые представленных в спецификации Web Applications 1.0,  и выделенных теперь в отдельную спецификацию W3C Web Storage. DOM хранилище было разработано с целью предоставления альтернативы хранению информации в кукисах. Предполагается, что DOM хранилище предоставляет больше объёма, оно более защищено и легче в использовании. Впервые оно было представлено  в браузерах Firefox 2 и Safari 4.

- -
Примечание: DOM хранилище - это не то же самое, что mozStorage (Mozilla's XPCOM interfaces to SQLite) или Session store API (утилита XPCOM - хранилище для использования в расширениях).
- -
-

Примечание: Эта статья скоро будет сильно переработана. Вместо того, чтобы хранить всю информацию на одной странице, она будет разбита на несколько статей, каждая из которых будет описывать разные API хранилища. Отдельная статья, помогающая разобраться в разных API, будет также добавлена.

-
- -

Описание

- -

Механизм DOM хранилища - средство, благодаря которому можно безопасно хранить и позже извлекать пары "ключ / значение". Целью этого является обеспечение комплексного средства, с помощью которого можно разрабатывать интерактивные приложения(включая приложения с продвинутыми возможностями, такими как возможность работать "автономно"("offline") в течение длительных периодов времени).

- -

Браузеры на основе Mozilla, Internet Explorer 8 +, Safari 4 + и Chrome обеспечивают рабочую реализацию спецификации DOM хранилища. (В случае, если нужна кросс-браузерная поддержка функциональности, включая более старые версии IE, будет полезно отметить, что IE также имеет подобную легаси функциональность под названием "USERDATA поведение", которая дополнение DOM хранилище IE в IE8.)

- -

DOM хранилище удобно, потому что нет других хороших способов хранения разумных объёмов данных за любой период времени, встроенных в браузер. Кукисы ограничены в количестве хранимой информации и не обеспечивают поддержку для организации постоянных данных, а другие методы (например, флэш-локальное хранилище) требуют плагина.

- -

Одним из первых известных приложений,  использующих новые функциональные возможности DOM хранилища(в дополнение к USERDATA поведения в Internet Explorer) было halfnote (приложение для заметок), написанное Аароном Будменом. В своём приложении, Аарон одновременно сохранял заметки на сервере (когда/если Интернет-подключение  был доступно) и локального хранилища данных(в обратном случае). Это дало возможность пользователю смело писать резервные копии заметок даже при нерегулярном подключении к Интернету.

- -

Хотя идея и реализация halfnote были сравнительно простыми, создание halfnote показывает возможность для нового поколения веб-приложений, которые можно использовать как в онлайн-, так и офлайн-режиме.

- -

Связь

- -

Ниже приведены глобальные объекты, которые существуют как свойства каждого объекта  window. Это означает, что они могут быть доступны как sessionStorage или window.sessionStorage. (Это важно, потому что вы можете использовать фреймы(IFrames) для хранения или доступа, дополнительные данные кроме того, что сразу же включено на странице.)

- -

Storage

- -

Это конструктор(Storageдля всех экземпляров Storage (sessionStorage и globalStorage[location.hostname]).

- -

Сохранение Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } будет доступно через localStorage.removeKey и sessionStorage.removeKey.

- -

Единицы globalStorage являются экземплярами StorageObsolete, а не Storage.

- -

Storage определён в WhatWG Storage Interface следующим образом:

- -
interface Storage {
-  readonly attribute unsigned long length;
-  [IndexGetter] DOMString key(in unsigned long index);
-  [NameGetter] DOMString getItem(in DOMString key);
-  [NameSetter] void setItem(in DOMString key, in DOMString data);
-  [NameDeleter] void removeItem(in DOMString key);
-  void clear();
-};
-
- -
Примечание: Несмотря на то, что значения доступны для чтения и записи через стандартные способы Javascript, рекомендуется использование getItem и setItem.
- -
Примечание: Обратите внимание, что любые данные, которые хранятся в любом из хранилищ, описанных на этой странице, преобразуются в строку, используя метод.toString. перед тем, как сохранить значение. Попытка сохранить объект приведёт к сохранению строки "[object Object]"  вместо объекта или его JSON представления. Самым лучшим и распространённым способом сохранения объектов в формате строки является использование предоставляемых браузером методов JSON для парсинга и сериализации объектов.
- -

sessionStorage

- -

Это глобальный объект (sessionStorage), который сохраняет значения, которые доступны в течение периода текущей сессии. Сессия страницы длится, пока браузер открыт, и восстанавливает свои значения после перегрузки страницы. Открытие страницы в новой вкладке или окне приведёт к созданию новой сессии для этой страницы.

- -
// Сохранить данные в локальное хранилище текущей сессии
-sessionStorage.setItem("username", "John");
-
-// Получить значения сохранённого значения
-alert( "username = " + sessionStorage.getItem("username"));
-
- -

Объект sessionStorage наиболее полезен для хранения временных данных, которые должны быть восстановлены, если страница браузер была случайно перегружена.

- -

Примеры:

- -

Автоматическое сохранение содержимого тестового поля, и если страница была случайно перегружена, то данные не будут потеряны.

- -
 // Получить значение текстового поля, которое мы собираемся отслеживать
- var field = document.getElementById("field");
-
- // Проверяем, что значение поля autosave существует
- // (это будет происходить при случайной перезагрузке страницы)
- if (sessionStorage.getItem("autosave")) {
-    // Восстановить значение тестового поля
-    field.value = sessionStorage.getItem("autosave");
- }
-
- // Обрабатывать изменения значения текстового поля
- field.addEventListener("change", function() {
-    // И сохранить результаты в объект хранилища сессий
-    sessionStorage.setItem("autosave", field.value);
- });
-
- -

Больше информации:

- - - -

localStorage

- -

localStorage - это то же самое, что и {{ Anch("sessionStorage") }}, поддерживает правила единого происхождения(same-origin rules), но хранение данных постоянно. localStorage был представлен в Firefox 3.5.

- -
Примечание: Когда браузер переходит в частный режим браузера(private browsing mode), то новая, временная база данных создаётся для хранения данных локального хранилища; эта база данных очищается и удаляется, как только частный режим браузера выключается.
- -

Совместимость

- -

Объекты Storage - относительно недавнее дополнение стандарта. Это означает, что они не обязательно должны быть реализованы во всех браузерах. Проблему можно решить с помощью включения следующего куска кода в начале вашего скрипта, позволяя использовать объект localStorage в реализациях, которые нативно не поддерживают его.

- -

Следующий алгоритм - это точная имитация объекта localStorage, но использует куки.

- -
if (!window.localStorage) {
-  Object.defineProperty(window, "localStorage", new (function () {
-    var aKeys = [], oStorage = {};
-    Object.defineProperty(oStorage, "getItem", {
-      value: function (sKey) { return sKey ? this[sKey] : null; },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "key", {
-      value: function (nKeyId) { return aKeys[nKeyId]; },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "setItem", {
-      value: function (sKey, sValue) {
-        if(!sKey) { return; }
-        document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
-      },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "length", {
-      get: function () { return aKeys.length; },
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "removeItem", {
-      value: function (sKey) {
-        if(!sKey) { return; }
-        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
-      },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    this.get = function () {
-      var iThisIndx;
-      for (var sKey in oStorage) {
-        iThisIndx = aKeys.indexOf(sKey);
-        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
-        else { aKeys.splice(iThisIndx, 1); }
-        delete oStorage[sKey];
-      }
-      for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
-      for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx < aCouples.length; nIdx++) {
-        aCouple = aCouples[nIdx].split(/\s*=\s*/);
-        if (aCouple.length > 1) {
-          oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]);
-          aKeys.push(iKey);
-        }
-      }
-      return oStorage;
-    };
-    this.configurable = false;
-    this.enumerable = true;
-  })());
-}
-
- -
Note: The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions localStorage.setItem() and localStorage.removeItem() to add, change, or remove a key. The use of methods localStorage.yourKey = yourValue; and delete localStorage.yourKey; to set or delete a key is not a secure way with this code. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.
- -
Note: By changing the string "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/" (and changing the object's name), this will become a sessionStorage polyfill rather than a localStorage polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant sessionStorage implementation restricts stored values to the current browsing context only.
- -

Here is another, less exact, imitation of the localStorage object. It is simpler than the previous one, but it is compatible with old browsers, like Internet Explorer < 8 (tested and working even in Internet Explorer 6). It also makes use of cookies.

- -
if (!window.localStorage) {
-  window.localStorage = {
-    getItem: function (sKey) {
-      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
-      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
-    },
-    key: function (nKeyId) {
-      return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
-    },
-    setItem: function (sKey, sValue) {
-      if(!sKey) { return; }
-      document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
-      this.length = document.cookie.match(/\=/g).length;
-    },
-    length: 0,
-    removeItem: function (sKey) {
-      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
-      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
-      this.length--;
-    },
-    hasOwnProperty: function (sKey) {
-      return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
-    }
-  };
-  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
-}
-
- -
Note: The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions localStorage.getItem(), localStorage.setItem(), and localStorage.removeItem() to get, add, change, or remove a key. The use of method localStorage.yourKey in order to get, set, or delete a key is not permitted with this code. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.
- -
Note: By changing the string "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/" (and changing the object's name), this will become a sessionStorage polyfill rather than a localStorage polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant sessionStorage implementation restricts stored values to the current browsing context only.
- -

Compatibility and relation with globalStorage

- -

localStorage is also the same as globalStorage[location.hostname], with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and localStorage being an instance of Storage as opposed to globalStorage[location.hostname] being an instance of StorageObsolete which is covered below. For example, http://example.com is not able to access the same localStorage object as https://example.com but they can access the same globalStorage item. localStorage is a standard interface while globalStorage is non-standard so you shouldn't rely on these.

- -

Please note that setting a property on globalStorage[location.hostname] does not set it on localStorage and extending Storage.prototype does not affect globalStorage items; only extending StorageObsolete.prototype does.

- -

globalStorage

- -
{{ Non-standard_header }}{{ obsolete_header("13.0") }}
- -

globalStorage is obsolete since Gecko 1.9.1 (Firefox 3.5) and unsupported since Gecko 13 (Firefox 13). Just use {{ Anch("localStorage") }} instead. This proposed addition to HTML5 has been removed from the HTML5 specification in favor of {{ Anch("localStorage") }}, which is implemented in Firefox 3.5. This is a global object (globalStorage) that maintains multiple private storage areas that can be used to hold data over a long period of time (e.g., over multiple pages and browser sessions).

- -
Note: globalStorage is not a Storage instance, but a StorageList instance containing StorageObsolete instances.
- -
// Save data that only scripts on the mozilla.org domain can access
-globalStorage['mozilla.org'].setItem("snippet", "<b>Hello</b>, how are you?");
-
- -

Specifically, the globalStorage object provides access to a number of different storage objects into which data can be stored. For example, if we were to build a web page that used globalStorage on this domain (developer.mozilla.org) we'd have the following storage object available to us:

- - - -

Examples:

- -

All of these examples require that you have a script inserted (with each of the following code) in every page that you want to see the result on.

- -

Remember a user's username for the particular sub-domain that is being visited:

- -
 globalStorage['developer.mozilla.org'].setItem("username", "John");
-
- -

Keep track of the number of times that a user visits all pages of your domain:

- -
 // parseInt must be used since all data is stored as a string
- globalStorage['mozilla.org'].setItem("visits", parseInt(globalStorage['mozilla.org'].getItem("visits") || 0 ) + 1);
-
- -

Расположение хранилища и очищение данных

- -

In Firefox the DOM storage data is stored in the webappsstore.sqlite file in the profile folder (there's also chromeappsstore.sqlite file used to store browser's own data, notably for the start page - about:home, but potentially for other internal pages with "about:" URLs).

- - - -

See also clearing offline resources cache.

- -

Больше информации

- - - -

Примеры

- - - -

Совместимость с браузерами

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
globalStorage{{ CompatNo }}2-13{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
-
- -

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.

- -
-

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.

-
- -

Полезные ссылки

- - - -
{{ HTML5ArticleTOC }}
diff --git a/files/ru/conflicting/web/api/webrtc_api/index.html b/files/ru/conflicting/web/api/webrtc_api/index.html deleted file mode 100644 index 6e7c0536eb..0000000000 --- a/files/ru/conflicting/web/api/webrtc_api/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: WebRTC -slug: conflicting/Web/API/WebRTC_API -translation_of: Web/API/WebRTC_API -translation_of_original: Web/Guide/API/WebRTC -original_slug: Web/Guide/API/WebRTC ---- -

WebRTC (где RTC расшифровывается как Real-Time Communications) - это технология, которая позволяет передавать данные и потоковое аудио/видео между браузерами. Как набор стандартов в целом, WebRTC предоставляет любым поддерживающим этот стандарт, браузерам обмениваться данными и устраивать сеансы телеконференций в режиме точка-точка, без необходимости устанавливать какие-либо плагины и стороннее программное обеспечение.

- -

Компоненты WebRTC доступны через API JavaScript: Network Stream API, который представляет собой поток аудио и видео данных, PeerConnection API, который позволяет двум и более пользователям общаться браузер-браузер напрямую, DataChannel API, который позволяет обмениваться данными других типов, например в играх в режиме реального времени, текстовые чаты, обмен файлами и так далее.

- -
-

На заметку: Эта документация находится в процессе переезда в свой новый дом.

-
- -

Руководства

- -
-
Обмен данными в режиме точка-точка с WebRTC
-
О том, как наладить обмен данными в режиме точка-точка используя API WebRTC.
-
Введение в архитектуру WebRTC
-
(AKA "WebRTC and the Ocean of Acronyms") WebRTC состоит из множества частей и это может быть причиной сложностей для новичков. Эта статья рассказывает обо всех частях и объясняет то как они между собой связаны.
-
Основы WebRTC
-
Теперь, когда вы уже знаете архитектуру WebRTC, вы можете перейти к этой статье, которая проведёт вас через путь создания кросс-браузерного RTC-приложения
-
- -

Ссылки

- -
-
MediaDevices.getUserMedia
-
API захвата медиа (видео/аудио)
-
RTCPeerConnection
-
Интерфейс обработки потоковых данных между двумя пирами.
-
RTCDataChannel
-
Интерфейс передачи произвольных данных через соединение точка-точка.
-
diff --git a/files/ru/conflicting/web/api/webrtc_api/signaling_and_video_calling/index.html b/files/ru/conflicting/web/api/webrtc_api/signaling_and_video_calling/index.html deleted file mode 100644 index fc0da52bbc..0000000000 --- a/files/ru/conflicting/web/api/webrtc_api/signaling_and_video_calling/index.html +++ /dev/null @@ -1,352 +0,0 @@ ---- -title: Основы WebRTC -slug: conflicting/Web/API/WebRTC_API/Signaling_and_video_calling -translation_of: Web/API/WebRTC_API/Signaling_and_video_calling -translation_of_original: Web/API/WebRTC_API/WebRTC_basics -original_slug: Web/API/WebRTC_API/WebRTC_basics ---- -

{{WebRTCSidebar}}

- -

{{Draft}}

- -
-

После того, как вы понимаете WebRTC architecture, вы можете прочитать эту статью, которая сопроводит вас через создание кросс-браузерного RTC приложения. К концу этой документации, вы должны иметь рабочие каналы соединения равноправных узлов ЛВС и передачи данных средств массовой информации.

-
- -

Полу-старое содержание, из

- -

RTCPeerConnection

- -

Материал здесь происходит от RTCPeerConnection; она может остаться здесь, или же  может переместится в другое место.

- -

Основы использования
- Базовое использование RTCPeerConnection предполагает переговоры связь между локальной машиной и удалённой машиной один генерируя Session Description Protocol для обмена между ними. Вызывающая программа начинает процесс, отправив предложение на удалённое устройство, которое реагирует либо принять или отклонить запрос на соединение.

- -

Обе стороны (вызывающий и вызываемый абонент) необходимо настроить свои собственные экземпляры RTCPeerConnection, чтобы представить их конец соединения равноправных узлов ЛВС:

- -
var pc = new RTCPeerConnection();
-pc.onaddstream = function(obj) {
-  var vid = document.createElement("video");
-  document.appendChild(vid);
-  vid.srcObject = obj.stream;
-}
-
-// функция помощник
-function endCall() {
-  var videos = document.getElementsByTagName("video");
-  for (var i = 0; i < videos.length; i++) {
-    videos[i].pause();
-  }
-
-  pc.close();
-
-
-function error(err) {
-  endCall();
-}
-
- -

При инициализации вызова

- -

Если вы один инициирующий вызов, вы будете использовать navigator.getUserMedia(), чтобы получить видеопоток, а затем добавить поток в RTCPeerConnection. Как только это было сделано, вызов RTCPeerConnection, чтобы создать предложение, настроить предложение, а затем отправить его на сервер, через  соединение которое было создано.

- -
// Получить список людей с сервера
-// Пользователь выбирает список людей, чтобы установить соединение с нужным человеком
-navigator.getUserMedia({video: true}, function(stream) {
-  // Добавление локального потока не вызовет колбэк onaddstream,
-  // так называют его вручную.
-  pc.onaddstream = e => video.src = URL.createObjectURL(e.stream);
-  pc.addStream(stream);
-
-  pc.createOffer(function(offer) {
-    pc.setLocalDescription(offer, function() {
-      // send the offer to a server to be forwarded to the friend you're calling.
-    }, error);
-  }, error);
-});
-
- -

Ответ на вызов

- -

На противоположном конце, друг получит предложение от сервера, используя любой протокол используется для того чтобы сделать это. После того, как предложение прибывает, {{domxref ("navigator.getUserMedia ()")}} вновь используется для создания потока, который добавляется к RTCPeerConnection. {{Domxref ("RTCSessionDescription")}} объект создаётся и установить в качестве удалённого описания с помощью вызова {{domxref ("RTCPeerConnection.setRemoteDescription ()")}}.

- -

Тогда ответ создаётся с помощью RTCPeerConnection.createAnswer () и отправляется обратно на сервер, который направляет его к вызывающему абоненту.

- -
var offer = getOfferFromFriend();
-navigator.getUserMedia({video: true}, function(stream) {
-  pc.onaddstream = e => video.src = URL.createObjectURL(e.stream);
-  pc.addStream(stream);
-
-  pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
-    pc.createAnswer(function(answer) {
-      pc.setLocalDescription(answer, function() {
-        // send the answer to a server to be forwarded back to the caller (you)
-      }, error);
-    }, error);
-  }, error);
-});
-
- -

Ответ на вызов

- -

На противоположном конце, человек получит предложение от сервера, используя любой протокол используется для того чтобы сделать это. После того, как предложение принято, navigator.getUserMedia () вновь используется для создания потока, который добавляется к RTCPeerConnection.  объект создаётся и установить в качестве удалённого описания с помощью вызова {{domxref ("RTCPeerConnection.setRemoteDescription ()")}}.

- -

Тогда ответ создаётся с помощью RTCPeerConnection.createAnswer () и отправляется обратно на сервер, который направляет его к вызывающему абоненту.

- -
// ПК был создан раньше, когда мы сделали первоначальное предложение
-var offer = getResponseFromFriend();
-pc.setRemoteDescription(new RTCSessionDescription(offer), function() { }, error);
- -

Old content follows!

- -

Все, что находится ниже этого пункта,  потенциально устарело. Это по-прежнему находится в стадии рассмотрения  и возможного включения в другие части документации, если они все ещё актуальны.

- -
-

Не используйте примеры на этой странице. Смотрите статью Signaling and video calling для работы, актуальный пример с использованием WebRTC media.

-
- -

Note

- -

Due to recent changes in the API there are many old examples that require fixing:

- - - -

The currently working example is:

- - - -

Implementation may be inferred from the specification.

- -

This remainder of this page contains outdated information as noted on bugzilla.

- -

Shims

- -

As you can imagine, with such an early API, you must use the browser prefixes and shim it to a common variable.

- -
var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
-var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
-var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
-navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
- -

RTCPeerConnection

- -

This is the starting point to creating a connection with a peer. It accepts configuration options about ICE servers to use to establish a connection.

- -
var pc = new RTCPeerConnection(configuration);
- -

RTCConfiguration

- -

The {{domxref("RTCConfiguration")}} object contains information about which TURN and/or STUN servers to use for ICE. This is required to ensure most users can actually create a connection by avoiding restrictions in NAT and firewalls.

- -
var configuration = {
-    iceServers: [
-        {urls: "stun:23.21.150.121"},
-        {urls: "stun:stun.l.google.com:19302"},
-        {urls: "turn:numb.viagenie.ca", credential: "webrtcdemo", username: "louis%40mozilla.com"}
-    ]
-}
- -

Google runs a public STUN server that we can use. I also created an account at http://numb.viagenie.ca/ for a free TURN server to access. You may want to do the same and replace with your own credentials.

- -

ICECandidate

- - - -

After creating the PeerConnection and passing in the available STUN and TURN servers, an event will be fired once the ICE framework has found some “candidates” that will allow you to connect with a peer. This is known as an ICE Candidate and will execute a callback function on PeerConnection#onicecandidate.

- -
pc.onicecandidate = function (e) {
-    // candidate exists in e.candidate
-    if (!e.candidate) return;
-    send("icecandidate", JSON.stringify(e.candidate));
-};
- -

When the callback is executed, we must use the signal channel to send the Candidate to the peer. On Chrome, multiple ICE candidates are usually found, we only need one so I typically send the first one then remove the handler. Firefox includes the Candidate in the Offer SDP.

- -

Signal Channel

- -

Now that we have an ICE candidate, we need to send that to our peer so they know how to connect with us. However this leaves us with a chicken and egg situation; we want PeerConnection to send data to a peer but before that we need to send them metadata…

- -

This is where the signal channel comes in. It’s any method of data transport that allows two peers to exchange information. In this article, we’re going to use FireBase because it’s incredibly easy to setup and doesn't require any hosting or server-code.

- -

For now just imagine two methods exist: send() will take a key and assign data to it and recv() will call a handler when a key has a value.

- -

The structure of the database will look like this:

- -
{
-    "": {
-        "candidate:": …
-        "offer": …
-        "answer": …
-    }
-}
- -

Connections are divided by a roomId and will store 4 pieces of information, the ICE candidate from the offerer, the ICE candidate from the answerer, the offer SDP and the answer SDP.

- -

Offer

- -

An Offer SDP (Session Description Protocol) is metadata that describes to the other peer the format to expect (video, formats, codecs, encryption, resolution, size, etc etc).

- -

An exchange requires an offer from a peer, then the other peer must receive the offer and provide back an answer.

- -
pc.createOffer(function (offer) {
-    pc.setLocalDescription(offer, function() {
-        send("offer", JSON.stringify(pc.localDescription);
-    }, errorHandler);
-}, errorHandler, options);
- -

errorHandler

- -

If there was an issue generating an offer, this method will be executed with error details as the first argument.

- -
var errorHandler = function (err) {
-    console.error(err);
-};
- -
options
- -

Options for the offer SDP.

- -
var options = {
-    offerToReceiveAudio: true,
-    offerToReceiveVideo: true
-};
- -

offerToReceiveAudio/Video tells the other peer that you would like to receive video or audio from them. This is not needed for DataChannels.

- -

Once the offer has been generated we must set the local SDP to the new offer and send it through the signal channel to the other peer and await their Answer SDP.

- -

Answer

- -

An Answer SDP is just like an offer but a response; sort of like answering the phone. We can only generate an answer once we have received an offer.

- -
recv("offer", function (offer) {
-    offer = new SessionDescription(JSON.parse(offer))
-    pc.setRemoteDescription(offer);
-
-    pc.createAnswer(function (answer) {
-        pc.setLocalDescription(answer, function() {
-            send("answer", JSON.stringify(pc.localDescription));
-        }, errorHandler);
-    }, errorHandler);
-});
- -

DataChannel

- -

I will first explain how to use PeerConnection for the DataChannels API and transferring arbitrary data between peers.

- -

Note: At the time of this article, interoperability between Chrome and Firefox is not possible with DataChannels. Chrome supports a similar but private protocol and will be supporting the standard protocol soon.

- -
var channel = pc.createDataChannel(channelName, channelOptions);
- -

The offerer should be the peer who creates the channel. The answerer will receive the channel in the callback ondatachannel on PeerConnection. You must call createDataChannel() once before creating the offer.

- -

channelName

- -

This is a string that acts as a label for your channel name. Warning: Make sure your channel name has no spaces or Chrome will fail on createAnswer().

- -

channelOptions

- -
var channelOptions = {};
- -

Currently these options are not well supported on Chrome so you can leave this empty for now. Check the RFC for more information about the options.

- -

Channel Events and Methods

- -
onopen
- -

Executed when the connection is established.

- -
onerror
- -

Executed if there is an error creating the connection. First argument is an error object.

- -
channel.onerror = function (err) {
-    console.error("Channel Error:", err);
-};
- -
onmessage
- -
channel.onmessage = function (e) {
-    console.log("Got message:", e.data);
-}
- -

The heart of the connection. When you receive a message, this method will execute. The first argument is an event object which contains the data, time received and other information.

- -
onclose
- -

Executed if the other peer closes the connection.

- -

Binding the Events

- -

If you were the creator of the channel (meaning the offerer), you can bind events directly to the DataChannel you created with createChannel. If you are the answerer, you must use the ondatachannel callback on PeerConnection to access the same channel.

- -
pc.ondatachannel = function (e) {
-    e.channel.onmessage = function () { … };
-};
- -

The channel is available in the event object passed into the handler as e.channel.

- -
send()
- -
channel.send("Hi Peer!");
- -

This method allows you to send data directly to the peer! Amazing. You must send either String, Blob, ArrayBuffer or ArrayBufferView, so be sure to stringify objects.

- -
close()
- -

Close the channel once the connection should end. It is recommended to do this on page unload.

- -

Media

- -

Now we will cover transmitting media such as audio and video. To display the video and audio you must include a <video> tag on the document with the attribute autoplay.

- -

Get User Media

- -
<video id="preview" autoplay></video>
-
-var video = document.getElementById("preview");
-navigator.getUserMedia(constraints, function (stream) {
-    video.src = URL.createObjectURL(stream);
-}, errorHandler);
- -

constraints

- -

Constraints on what media types you want to return from the user.

- -
var constraints = {
-    video: true,
-    audio: true
-};
- -

If you just want an audio chat, remove the video member.

- -
errorHandler
- -

Executed if there is an error returning the requested media.

- -

Media Events and Methods

- -
addStream
- -

Add the stream from getUserMedia to the PeerConnection.

- -
pc.addStream(stream);
- -
onaddstream
- -
<video id="otherPeer" autoplay></video>
-
-var otherPeer = document.getElementById("otherPeer");
-pc.onaddstream = function (e) {
-    otherPeer.src = URL.createObjectURL(e.stream);
-};
- -

Executed when the connection has been setup and the other peer has added the stream to the peer connection with addStream. You need another <video> tag to display the other peer's media.

- -

The first argument is an event object with the other peer's media stream.

diff --git a/files/ru/conflicting/web/api/window/localstorage/index.html b/files/ru/conflicting/web/api/window/localstorage/index.html deleted file mode 100644 index 5e87d8edc8..0000000000 --- a/files/ru/conflicting/web/api/window/localstorage/index.html +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: LocalStorage -slug: conflicting/Web/API/Window/localStorage -translation_of: Web/API/Window/localStorage -translation_of_original: Web/API/Web_Storage_API/Local_storage -original_slug: Web/API/Storage/LocalStorage ---- -

localStorage это аналог sessionStorage, с некоторыми same-origin правилами, но значения хранятся постоянно (в отличии от sessions). localStorage появился в Firefox 3.5.

- -
Примечание: Когда браузер переходит в режим приватного просмотра, создаётся новое временное хранилище. Изначально оно пустое. После выхода из режима приватного просмотра временное хранилище очищается.
- -
// Сохраняет данные в текущий local store
-localStorage.setItem("username", "John");
-
-// Извлекает ранее сохранённые данные
-alert( "username = " + localStorage.getItem("username"));
- -

localStorage's позволяет постоянно хранить некоторую полезную информацию, включая счётчики посещения страницы, как показано в примере this tutorial on Codepen.

- -

Совместимость

- -

Storage objects недавно добавлен в стандарт. Он может отсутствовать в некоторых браузерах. Вы можете работать с этой технологией добавив в страницу один из двух скриптов, которые представлены ниже. localStorage object реализуется программно, если нет встроенной реализации.

- -

Этот алгоритм является точной имитацией localStorage object, но для хранения использует cookies.

- -
if (!window.localStorage) {
-  Object.defineProperty(window, "localStorage", new (function () {
-    var aKeys = [], oStorage = {};
-    Object.defineProperty(oStorage, "getItem", {
-      value: function (sKey) { return sKey ? this[sKey] : null; },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "key", {
-      value: function (nKeyId) { return aKeys[nKeyId]; },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "setItem", {
-      value: function (sKey, sValue) {
-        if(!sKey) { return; }
-        document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
-      },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "length", {
-      get: function () { return aKeys.length; },
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "removeItem", {
-      value: function (sKey) {
-        if(!sKey) { return; }
-        document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
-      },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    Object.defineProperty(oStorage, "clear", {
-      value: function () {
-        if(!aKeys.length) { return; }
-        for (var sKey in aKeys) {
-          document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
-        }
-      },
-      writable: false,
-      configurable: false,
-      enumerable: false
-    });
-    this.get = function () {
-      var iThisIndx;
-      for (var sKey in oStorage) {
-        iThisIndx = aKeys.indexOf(sKey);
-        if (iThisIndx === -1) { oStorage.setItem(sKey, oStorage[sKey]); }
-        else { aKeys.splice(iThisIndx, 1); }
-        delete oStorage[sKey];
-      }
-      for (aKeys; aKeys.length > 0; aKeys.splice(0, 1)) { oStorage.removeItem(aKeys[0]); }
-      for (var aCouple, iKey, nIdx = 0, aCouples = document.cookie.split(/\s*;\s*/); nIdx < aCouples.length; nIdx++) {
-        aCouple = aCouples[nIdx].split(/\s*=\s*/);
-        if (aCouple.length > 1) {
-          oStorage[iKey = unescape(aCouple[0])] = unescape(aCouple[1]);
-          aKeys.push(iKey);
-        }
-      }
-      return oStorage;
-    };
-    this.configurable = false;
-    this.enumerable = true;
-  })());
-}
-
- -
Примечание: Максимальный размер данных, которые могут быть сохранены, ограничен возможностями cookies. Используйте functions localStorage.setItem() и localStorage.removeItem() для добавления, изменения, или удаления ключа. Использование прямого присвоения localStorage.yourKey = yourValue; и delete localStorage.yourKey; для установки и удаления ключа не безопасно с этим кодом. Вы также можете изменить это имя (вместо window.localStorage прописать другое имя) и использовать объект для управления document's cookies, не обращая внимания на localStorage object.
- -
Примечание: Если изменить строку "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" на: "; path=/" (и изменить имя объекта), он превратится в sessionStorage polyfill больше, чем в localStorage polyfill. Однако эта реализация будет хранить общие значения для всех вкладок и окон браузера (and will only be cleared when all browser windows have been closed), в то время как полностью совместимая sessionStorage реализация хранит значения to the current browsing context only.
- -

Here is another, less exact, imitation of the localStorage object. It is simpler than the previous one, but it is compatible with old browsers, like Internet Explorer < 8 (tested and working even in Internet Explorer 6). It also makes use of cookies.

- -
if (!window.localStorage) {
-  window.localStorage = {
-    getItem: function (sKey) {
-      if (!sKey || !this.hasOwnProperty(sKey)) { return null; }
-      return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
-    },
-    key: function (nKeyId) {
-      return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
-    },
-    setItem: function (sKey, sValue) {
-      if(!sKey) { return; }
-      document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/";
-      this.length = document.cookie.match(/\=/g).length;
-    },
-    length: 0,
-    removeItem: function (sKey) {
-      if (!sKey || !this.hasOwnProperty(sKey)) { return; }
-      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
-      this.length--;
-    },
-    hasOwnProperty: function (sKey) {
-      return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
-    }
-  };
-  window.localStorage.length = (document.cookie.match(/\=/g) || window.localStorage).length;
-}
-
- -
Note: The maximum size of data that can be saved is severely restricted by the use of cookies. With this algorithm, use the functions localStorage.getItem()localStorage.setItem(), and localStorage.removeItem() to get, add, change, or remove a key. The use of method localStorage.yourKey in order to get, set, or delete a key is not permitted with this code. You can also change its name and use it only to manage a document's cookies regardless of the localStorage object.
- -
Note: By changing the string "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/" to: "; path=/" (and changing the object's name), this will become a sessionStorage polyfill rather than a localStorage polyfill. However, this implementation will share stored values across browser tabs and windows (and will only be cleared when all browser windows have been closed), while a fully-compliant sessionStorage implementation restricts stored values to the current browsing context only.
- -

Compatibility and relation with globalStorage

- -

localStorage is also the same as globalStorage[location.hostname], with the exception of being scoped to an HTML5 origin (scheme + hostname + non-standard port) and localStorage being an instance of Storage as opposed to globalStorage[location.hostname] being an instance of StorageObsolete which is covered below. For example, http://example.com is not able to access the same localStorage object as https://example.com but they can access the same globalStorage item. localStorage is a standard interface while globalStorage is non-standard so you shouldn't rely on these.

- -

Please note that setting a property on globalStorage[location.hostname] does not set it on localStorage and extending Storage.prototype does not affect globalStorage items; only extending StorageObsolete.prototype does.

- -

Storage format

- -

Storage keys and values are both stored in the UTF-16 DOMString format, which uses 2 bytes per character.

- -

 

diff --git a/files/ru/conflicting/web/api/windoworworkerglobalscope/index.html b/files/ru/conflicting/web/api/windoworworkerglobalscope/index.html deleted file mode 100644 index 69bc73a64f..0000000000 --- a/files/ru/conflicting/web/api/windoworworkerglobalscope/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: WindowBase64 -slug: conflicting/Web/API/WindowOrWorkerGlobalScope -tags: - - API - - HTML-DOM - - Helper - - NeedsTranslation - - TopicStub - - WindowBase64 -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowBase64 -original_slug: Web/API/WindowBase64 ---- -

{{APIRef("HTML DOM")}}

- -

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

- -

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

- -

Properties

- -

This helper neither defines nor inherits any properties.

- -

Methods

- -

This helper does not inherit any methods.

- -
-
{{domxref("WindowBase64.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowBase64.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

- -

See also

- - diff --git a/files/ru/conflicting/web/api/windoworworkerglobalscope_e2691f7ad05781a30c5fc5bb3b3f633a/index.html b/files/ru/conflicting/web/api/windoworworkerglobalscope_e2691f7ad05781a30c5fc5bb3b3f633a/index.html deleted file mode 100644 index 21a473532e..0000000000 --- a/files/ru/conflicting/web/api/windoworworkerglobalscope_e2691f7ad05781a30c5fc5bb3b3f633a/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: WindowTimers -slug: conflicting/Web/API/WindowOrWorkerGlobalScope_e2691f7ad05781a30c5fc5bb3b3f633a -tags: - - API - - HTML DOM -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowTimers -original_slug: Web/API/WindowTimers ---- -
{{APIRef("HTML DOM")}}
- -

WindowTimers contains utility methods to set and clear timers.

- -

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

- -

Properties

- -

This interface do not define any property, nor inherit any.

- -

Methods

- -

This interface do not inherit any method.

- -
-
{{domxref("WindowTimers.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
-
{{domxref("WindowTimers.clearTimeout()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
-
{{domxref("WindowTimers.setInterval()")}}
-
Schedules the execution of a function each X milliseconds.
-
{{domxref("WindowTimers.setTimeout()")}}
-
Sets a delay for executing a function.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

See also

- - diff --git a/files/ru/conflicting/web/api/xmlhttprequest/index.html b/files/ru/conflicting/web/api/xmlhttprequest/index.html deleted file mode 100644 index 10503ded9b..0000000000 --- a/files/ru/conflicting/web/api/xmlhttprequest/index.html +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: XMLHttpRequest -slug: conflicting/Web/API/XMLHttpRequest -tags: - - AJAX - - XMLHttpRequest -original_slug: XMLHttpRequest ---- -

XMLHttpRequest — это объект JavaScript, созданный Microsoft и адаптированный Mozilla. Вы можете использовать его для простой передачи данных через HTTP. Несмотря на своё название, он может быть использован не только для XML документов, но и, например, для JSON.

- -

Оставшаяся часть статьи может содержать информацию, специфичную для Gecko или привилегированного кода, такого как дополнения.

- -

В Gecko этот объект реализует интерфейсы nsIJSXMLHttpRequest и nsIXMLHttpRequest. Недавние версии Gecko содержат некоторые изменения для этого объекта (см. XMLHttpRequest changes for Gecko1.8).

- -

Основы использования

- -

Использовать XMLHttpRequest очень просто. Вы создаёте экземпляр объекта, открываете URL и отправляете запрос. Статус HTTP-ответа, так же как и возвращаемый документ, доступны в свойствах объекта запроса.

- -
Замечание: Версии Firefox до версии 3 постоянно отправляют запрос, используя кодировку UTF-8. Отправляя документ, Firefox 3 использует кодировку, определённую в data.inputEncoding (где data — ненулевой объект, переданный в send()). Если не определено, то используется UTF-8.
- -

Пример

- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', false);
-req.send(null);
-if(req.status == 200)
-  dump(req.responseText);
-
- -
Замечание: Этот пример работает синхронно, то есть он заблокирует интерфейс пользователя, если вы вызовете его из своего кода. Не рекомендуется использовать это на практике.
- -

Пример без http протокола

- -
var req = new XMLHttpRequest();
-req.open('GET', 'file:///home/user/file.json', false);
-req.send(null);
-if(req.status == 0)
-  dump(req.responseText);
-
- -
Замечание: file:/// и ftp:// не возвращают HTTP статуса, вот почему они возвращают ноль в status и пустую строчку в statusText. См. {{ Bug(331610) }} для подробной информации.
- -

Асинхронное использование

- -

Если вы собираетесь использовать XMLHttpRequest из дополнения, вы должны позволить ему загружаться асинхронно. Во время асинхронного использования вы получаете отзыв после загрузки данных, что позволяет браузеру продолжать работу пока ваш запрос обрабатывается.

- -

Пример

- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', true); /* Третий аргумент true означает асинхронность */
-req.onreadystatechange = function (aEvt) {
-  if (req.readyState == 4) {
-     if(req.status == 200)
-      dump(req.responseText);
-     else
-      dump("Error loading page\n");
-  }
-};
-req.send(null);
-
- -

Наблюдение за прогрессом

- -

XMLHttpRequest предоставляет возможность отлавливать некоторые события которые могут возникнуть во время обработки запроса. Включая периодические уведомления о прогрессе, сообщения об ошибках и так далее.

- -

Если к примеру вы желаете предоставить информацию пользователю о прогрессе получения документа, вы можете использовать код вроде этого:

- -
function onProgress(e) {
-  var percentComplete = (e.position / e.totalSize)*100;
-  ...
-}
-
-function onError(e) {
-  alert("Error " + e.target.status + " occurred while receiving the document.");
-}
-
-function onLoad(e) {
-  // ...
-}
-// ...
-var req = new XMLHttpRequest();
-req.onprogress = onProgress;
-req.open("GET", url, true);
-req.onload = onLoad;
-req.onerror = onError;
-req.send(null);
-
- -

Атрибуты события onprogress: position и totalSize, отображают соответственно текущие количество принятых байтов и количество ожидаемых байтов.

- -

Все эти события имеют свои target атрибуты установленные в соответствии с XMLHttpRequest.

- -
Замечание: Firefox 3 по сути обеспечивает установку значений-ссылок полей target, currentTarget и this у объекта события на правильные объекты во время вызова обработчика событий для XML документов представленных в XMLDocument. См. {{ Bug(198595) }} для деталей.
- -

Другие Свойства и Методы

- -

В дополнение к свойствам и методам описанным выше, ниже следуют другие полезные свойства и методы для объекта запроса.

- -

responseXML

- -

Если вы загрузили XML документ свойство responseXML будет содержать документ в виде XmlDocument объекта которым вы можете манипулировать используя DOM методы. Если сервер отправляет правильно сформированные XML документы но не устанавливает Content-Type заголовок для него, вы можете использовать overrideMimeType() для того чтобы документ был обработан как XML. Если сервер не отправляет правильно сформированного документа XML, responseXML вернёт null независимо от любых перезаписей Content-Type заголовка.

- -

overrideMimeType()

- -

Этот метод может быть использован для обработки документа особенным образом. Обычно вы будете использовать его, когда запросите responseXML, и сервер отправит вам XML, но не отправит правильного Content-Type заголовка.

- -
Замечание: Этот метод должен вызываться до вызова send().
- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', true);
-req.overrideMimeType('text/xml');
-req.send(null);
-
- -

setRequestHeader()

- -

Этот метод может быть использован чтобы установить HTTP заголовок в запросе до его отправки.

- -
Замечание: вы должны вызвать вначале open().
- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', true);
-req.setRequestHeader("X-Foo", "Bar");
-req.send(null);
-
- -

getResponseHeader()

- -

Этот метод может быть использован для получения HTTP заголовка из ответа сервера.

- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', false);
-req.send(null);
-dump("Content-Type: " + req.getResponseHeader("Content-Type") + "\n");
-
- -

abort()

- -

Этот метод может быть использован чтобы отменить обрабатываемый запрос.

- -
var req = new XMLHttpRequest();
-req.open('GET', 'http://www.mozilla.org/', false);
-req.send(null);
-req.abort();
-
- -

mozBackgroundRequest

- -

Это свойство может быть использовано чтобы уберечь от всплытия аутентификации и неправильных диалогов сертификации в ответ на запрос. Также запрос не будет отменён при закрытии его окна, которому он принадлежит. Это свойство работает только для кода chrome.

- -
var req = new XMLHttpRequest();
-req.mozBackgroundRequest = true;
-req.open('GET', 'http://www.mozilla.org/', true);
-req.send(null);
-
- -

Using from XPCOM components

- -
Note: Changes are required if you use XMLHttpRequest from a JavaScript XPCOM component.
- -

XMLHttpRequest cannot be instantiated using the XMLHttpRequest() constructor from a JavaScript XPCOM component. The constructor is not defined inside components and the code results in an error. You'll need to create and use it using a different syntax.

- -

Instead of this:

- -
var req = new XMLHttpRequest();
-req.onprogress = onProgress;
-req.onload = onLoad;
-req.onerror = onError;
-req.open("GET", url, true);
-req.send(null);
-
- -

Do this:

- -
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
-                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
-req.onprogress = onProgress;
-req.onload = onLoad;
-req.onerror = onError;
-req.open("GET", url, true);
-req.send(null);
-
- -

For C++ code you would need to QueryInterface the component to an nsIEventTarget in order to add event listeners, but chances are in C++ using a channel directly would be better.

- -

Limited number of simultaneous XMLHttpRequest connections

- -

The about:config preference: network.http.max-persistent-connections-per-server limits the number of connections. In Firefox 3 this value is 6 by default, previous versions use 2 as the default. Some interactive web pages using xmlHttpRequest may keep a connection open. Opening two or three of these pages in different tabs or on different windows may cause the browser to hang in such a way that the window no longer repaints and browser controls don't respond.

- -

Binary Content

- -

Although less typical than sending/receiving character-oriented content, XMLHttpRequest can be used to send and receive binary content.

- -

Retrieving binary content

- -
// Fetches BINARY FILES synchronously using XMLHttpRequest
-function load_binary_resource(url) {
-  var req = new XMLHttpRequest();
-  req.open('GET', url, false);
-  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
-  req.overrideMimeType('text/plain; charset=x-user-defined');
-  req.send(null);
-  if (req.status != 200) return '';
-  return req.responseText;
-}
-
-var filestream = load_binary_resource(url);
-// x is the offset (i.e. position) of the byte in the returned binary file stream. The valid range for x is from 0 up to filestream.length-1.
-var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)
-
- -

See downloading binary streams with XMLHttpRequest for a detailed explanation. See also downloading files.

- -

Sending binary content

- -

This example POSTs binary content asynchronously. aBody is some data to send.

- -
 var req = new XMLHttpRequest();
- req.open("POST", url, true);
- // set headers and mime-type appropriately
- req.setRequestHeader("Content-Length", 741);
- req.sendAsBinary(aBody);
-
- -

You can also send binary content by passing an instance of interface nsIFileInputStream to req.send(). In that case, there is not need to set the Content-Length request header:

- -
// Make a stream from a file. The file variable holds an nsIFile
-var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
-                       .createInstance(Components.interfaces.nsIFileInputStream);
-stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance
-
-// Try to determine the MIME type of the file
-var mimeType = "text/plain";
-try {
-  var mimeService = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
-  mimeType = mimeService.getTypeFromFile(file); // file is an nsIFile instance
-}
-catch(e) { /* eat it; just use text/plain */ }
-
-// Send
-var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
-                    .createInstance(Components.interfaces.nsIXMLHttpRequest);
-req.open('PUT', url, false); /* synchronous! */
-req.setRequestHeader('Content-Type', mimeType);
-req.send(stream);
-
- -

Bypassing cache

- -

Normally, XMLHttpRequest attempts to retrieve content from local cache. To bypass this attempt, do the following:

- -
 var req = new XMLHttpRequest();
- req.open('GET', url, false);
- req.channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
- req.send(null);
-
- -

An alternative approach to bypassing cache, as described here:

- -
 var req = new XMLHttpRequest();
- req.open("GET", url += (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime(), false);
- req.send(null);
-
- -

This appends a timestamp URL parameter to the URL, taking care to insert a ? or & as appropriate. For example, http://foo.com/bar.html becomes http://foo.com/bar.html?12345 and http://foo.com/bar.html?foobar=baz becomes http://foo.com/bar.html?foobar=baz&12345. Since local cache is indexed by URL, the idea is that every URL used by XMLHttpRequest is unique, bypassing the cache.

- -

Downloading JSON and JavaScript in extensions

- -

Extensions shouldn't use eval() on JSON or JavaScript downloaded from the web. See Downloading JSON and JavaScript in extensions for details.

- -

References

- -
    -
  1. MDC AJAX introduction
  2. -
  3. XMLHttpRequest - REST and the Rich User Experience
  4. -
  5. XULPlanet documentation
  6. -
  7. Microsoft documentation
  8. -
  9. Apple developers' reference
  10. -
  11. "Using the XMLHttpRequest Object" (jibbering.com)
  12. -
  13. The XMLHttpRequest Object: W3C Working Draft
  14. -
- -

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "cn/XMLHttpRequest" } ) }}

-- cgit v1.2.3-54-g00ecf