Устаревшие и удаленные API в Chrome 49

Практически в каждой версии Chrome мы видим значительное количество обновлений и улучшений продукта, его производительности, а также возможностей веб-платформы.

В Chrome 49 (бета-версия от 2 февраля 2016 г., предполагаемая дата выхода стабильной версии: март 2016 г.) в Chrome внесен ряд изменений.

Использование префикса «css» в getComputedStyle(e).cssX устарело.

TL;DR : Использование префикса "css" в getComputedStyle(e) устарело, поскольку он не был частью формальной спецификации .

getComputedStyle is a great little function. It will return all CSS values of the DOM element's styles as they have been computed by the rendering engine. So for example, you could run getComputedStyle(_someElement_).height and it might return 224.1px because that is the height of the element as it is currently displayed.

Кажется, API довольно удобный. Так что же мы меняем?

До того, как движок рендеринга Chrome был переключен на Blink, он работал на базе WebKit, что позволяло добавлять префикс «css» к началу свойства. Например, getComputedStyle(e).cssHeight вместо getComputedStyle(e).height . Оба метода возвращали одни и те же данные, поскольку соответствовали одним и тем же базовым значениям, но именно такое использование префикса «css» нестандартно и было объявлено устаревшим и удалено.

Примечание. cssFloat является стандартным свойством и не подпадает под действие этого устаревания.

Если вы таким образом получите доступ к свойству в Chrome 49, оно вернет undefined , и вам придется исправить свой код.

Использование initTouchEvent устарело

TL;DR : initTouchEvent устарел в пользу constructor TouchEvent для улучшения соответствия спецификации и будет полностью удален в Chrome 54.

Намерение устранить проблему CRBug в Chromestatus Tracker

For a long time you have been able to create synthetic touch events in Chrome using the initTouchEvent API, these are frequently used to simulate Touch Events either for testing or automating some UI in your site. In Chrome 49 we have deprecated this API and will display the following warning with the intention to remove it completely in Chrome 53.

Метод TouchEvent.initTouchEvent устарел и будет удалён в версии M53, примерно в сентябре 2016 года. Вместо этого используйте конструктор TouchEvent.
'TouchEvent.initTouchEvent' is deprecated and will be removed in M53, around September 2016. Please use the TouchEvent constructor instead. See https://www.chromestatus.com/features/5730982598541312 for more details.

There are a number of reasons why this change is good . It is also not in the Touch Events spec. The Chrome implementation of initTouchEvent was not compatible at all with Safari's initTouchEvent API and was different to Firefox on Android's. And finally, the TouchEvent constructor is a lot easier to use.

It was decided that we will aim to follow the spec rather than maintain an API that is neither specced nor compatible with the only other implementation. Consequently we are first deprecating and then removing the initTouchEvent function and requiring developers to use the TouchEvent constructor.

There is usage of this API on the Web but we know it is used by a relatively low number of sites so we are not removing it as quickly as we might normally. We do believe that some of the usage is broken due to sites not handling Chrome's version of the signature.

Поскольку реализации API initTouchEvent для iOS и Android/Chrome настолько сильно различались, вам часто приходилось иметь код примерно такого содержания (часто забывая о Firefox):

    var event = document.createEvent('TouchEvent');
    
    if(ua === 'Android') {
      event.initTouchEvent(touchItem, touchItem, touchItem, "touchstart", window,
        300, 300, 200, 200, false, false, false, false);
    } else {
      event.initTouchEvent("touchstart", false, false, window, 0, 300, 300, 200,
        200, false, false, false, false, touches, targetTouches, changedTouches, 0, 0);
    }
    
    document.body.dispatchEvent(touchEvent);

Firstly, this is bad because it looks for "Android" in the User-Agent and Chrome on Android will match and hit this deprecation. It can't be removed just yet though because there will be other WebKit and older Blink based browsers on Android for a while that you will still need to support the older API.

To correctly handle TouchEvents on the web you should change your code to support Firefox, IE Edge, and Chrome by checking for the existence of TouchEvent on the window object and if it has a positive "length" (indicating it's a constructor that takes an argument) you should use that.

    if('TouchEvent' in window && TouchEvent.length > 0) {
      var touch = new Touch({
        identifier: 42,
        target: document.body,
        clientX: 200,
        clientY: 200,
        screenX: 300,
        screenY: 300,
        pageX: 200,
        pageY: 200,
        radiusX: 5,
        radiusY: 5
      });
    
      event = new TouchEvent("touchstart", {
        cancelable: true,
        bubbles: true,
        touches: [touch],
        targetTouches: [touch],
        changedTouches: [touch]
      });
    }
    else {
      event = document.createEvent('TouchEvent');
    
      if(ua === 'Android') {
        event.initTouchEvent(touchItem, touchItem, touchItem, "touchstart", window,
          300, 300, 200, 200, false, false, false, false);
      } else {
        event.initTouchEvent("touchstart", false, false, window, 0, 300, 300, 200,
          200, false, false, false, false, touches, targetTouches, 
          changedTouches, 0, 0);
      }
    }
    
    document.body.dispatchEvent(touchEvent);

Обработчики ошибок и успешного завершения, необходимые в методах RTCPeerConnection

TL;DR: The WebRTC RTCPeerConnection methods createOffer() and createAnswer() now require an error handler as well as a success handler. Previously it had been possible to call these methods with only a success handler. That usage is deprecated.

In Chrome 49 we've also added a warning if you call setLocalDescription() or setRemoteDescription() without supplying an error handler. We expect to make the error handler argument mandatory for these methods in Chrome 50.

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

Вот пример из демонстрации WebRTC RTCPeerConnection ( main.js, строка 126 ):

    function onCreateOfferSuccess(desc) {
      pc1.setLocalDescription(desc, function() {
         onSetLocalSuccess(pc1);
      }, onSetSessionDescriptionError);
      pc2.setRemoteDescription(desc, function() {
        onSetRemoteSuccess(pc2);
      }, onSetSessionDescriptionError);
      pc2.createAnswer(onCreateAnswerSuccess, onCreateSessionDescriptionError);
    }

Обратите внимание, что и setLocalDescription() и setRemoteDescription() всегда имели параметр обработчика ошибок, поэтому простое указание этого параметра является безопасным изменением.

В целом, для производственных приложений WebRTC мы рекомендуем использовать adapter.js — оболочку, поддерживаемую проектом WebRTC, чтобы изолировать приложения от изменений спецификаций и различий префиксов.

Document.defaultCharset устарел

TL;DR : Document.defaultCharset устарел для улучшения соответствия спецификации.

Намерение устранить проблему CRBug в Chromestatus Tracker

The Document.defaultCharset is a read-only property that returns the default character encoding of the user's system based on their regional settings. It's not been found to be useful to maintain this value because of the way that browsers use the character encoding information in the HTTP Response or in the meta tag embedded in the page.

By using document.characterSet you will get the first value specified in the HTTP header. If that is not present then you will get the value specified in the charset attribute of the <meta> element (for example, <meta charset="utf-8"> ). Finally if none of those are available the document.characterSet will be the user's system setting.

Gecko has not supported this property and it is not cleanly specced so this property will be deprecated from Blink in Chrome 49 (Beta in January 2016). The following warning will appear in your console until the removal of the property in Chrome 50:

«Document.defaultCharset» устарел и будет удалён в версии M50, примерно в апреле 2016 г.
«Document.defaultCharset» устарел и будет удален в версии M50, примерно в апреле 2016 г. Подробнее см. по ссылке https://www.chromestatus.com/features/6217124578066432 .

Более подробное обсуждение причин не указывать это в спецификации можно прочитать на github : https://github.com/whatwg/dom/issues/58

getStorageUpdates() удален

TL;DR : Navigator.getStorageUpdates() был удален, так как его больше нет в спецификации Navigator .

Намерение устранить проблему CRBug в Chromestatus Tracker

Если это кого-то затронет, я съем свою шляпу. getStorageUpdates() практически никогда (если вообще когда-либо) использовался в Интернете.

Процитируем (очень старую версию) спецификации HTML5:

Звучит круто, правда? В спецификации даже используется слово «whence» (которое, кстати, единственный раз встречается в спецификации). На уровне спецификации существовал StorageMutex , который управлял доступом к блокируемому хранилищу, такому как localStorage и файлы cookie, и этот API помогал освободить этот мьютекс, чтобы другие скрипты не блокировались этим StorageMutex . Но он так и не был реализован, не поддерживается ни в IE, ни в Gecko, а реализация WebKit (и, следовательно, Blink) оказалась пустой операцией.

Его уже давно убрали из спецификаций, а также полностью убрали из Blink (долгое время он был пустой операцией и ничего не делал, даже если его вызывали).

В маловероятном случае, если у вас есть код, вызывающий navigator.getStorageUpdates() то вам придется проверить наличие функции перед ее вызовом.

Object.observe() устарел

TL;DR : Object.observe() устарел, поскольку больше не находится на пути стандартизации и будет удален в будущем выпуске.

Намерение устранить проблему CRBug в Chromestatus Tracker

In November 2015 it was announced that Object.Observe was being withdrawn from TC39 . It has been deprecated from Chrome 49 and you will see the following warning in the console if you try to use it:

«Object.observe» устарел и будет удалён в версии M50, примерно в апреле 2016 года.
«Object.observe» устарел и будет удален в версии M50, примерно в апреле 2016 г. Подробнее см. по ссылке https://www.chromestatus.com/features/6147094632988672 .

Many developers liked this API and if you have been experimenting with it and are now seeking a transition path, consider using a polyfill such as MaxArt2501/object-observe or a wrapper library like polymer/observe-js .