LoginSignup
1
2

More than 3 years have passed since last update.

[Microsoft Edge]MutationObserverでattributeFilterを使った場合にSyntax Errorになる問題について

Posted at

概要

Firefox, Chrome等においてMutationObserverattributeFilterを使った場合には動作するが、EdgeではSyntax Errorが発生した際の覚書

コード


const ob = new MutationObserver((mutations, observer)=> {
  console.log(mutations, observer)
})

ob.observe(document, {
  childList: true,
  subtree: true,
  attributeFilter: ["height"],
})

子要素の追加や削除高さの変更を見ようとこのようなコードを書いたが、このコードはEdgeだと構文エラーになる
attributeFilter: ["height"]を指定しても検知される変更はElement.heightの値だけなのでスタイルの変更や内容の変化からの高さの変化自体は検知されません。

修正版

const ob = new MutationObserver((mutations, observer)=> {
  console.log(mutations, observer)
})

ob.observe(document, {
  attributes: true,
  childList: true,
  subtree: true,
  attributeFilter: ["height"],
})

attributes: true この一行を追加したら問題なくなる

原因

Stack OverFlowで下記の回答を見つけた。

With a MutationObserver, it's possible to filter attributes, but only if you are observing element attributes to begin with. Therefore the option attributeFilter is only applicable if attributes is set to true.

If you specify an attributeFilter without setting attributes to true, then IE11 will throw a syntax error, while Chrome and Firefox will just silently ignore attributeFilter.

To resolve the syntax error, either set attributes to true or remove the attributeFilter.

つまりattributeFilterを使うにはattributesを有効にしておく必要がある。
ChromeやFirefoxではattributesを有効にせずにattributeFilterを利用するとattributeFilterの設定をエラー出さずに無視するが、IE11(Edgeでも)ではsyntax errorになるとの事。

確かにattributesを有効にするとEdgeでエラーは出なくなるのだが、MDNでは

If this property is specified, there's no need to also set attributes to true, as it's implied

とのようにattributeFilterを指定していればattributestrueにする必要は無いとの記述を見つけたので試してみた。

検証

ブラウザ attributeFilterとattributes attributeFilterのみ
Edge 問題なし Syntax Error
Chrome 問題なし 問題なし
Firefox 問題なし 問題なし

という結果になった。

あとがき

今回の検証ではChromium ベースでない古いEdgeを利用したので、新しい方ではChromeやFirefoxと同じ挙動になるかも。
とりあえず、attributeFilter使う際はattributesも設定しておくと良いかも。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2