teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

Page Visibility API

2016/05/12 22:07

投稿

think49
think49

スコア18194

answer CHANGED
@@ -19,4 +19,32 @@
19
19
  - [HTMLMediaElement - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#Browser_compatibility)
20
20
  - [Media formats supported by the HTML audio and video elements - HTML | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats#Browser_compatibility)
21
21
 
22
+ ### Page Visibility API
23
+
24
+ iOS Safari では `window.onfocus` が動作しないようなので Page Visibility API を併用します。
25
+
26
+ - [Page Visibility - Can I use...](http://caniuse.com/#feat=pagevisibility)
27
+
28
+ ```javascript
29
+ 'use strict';
30
+ function handleVisibilitychange (event) {
31
+ var doc = event.target;
32
+
33
+ if (doc.visibilityState === 'visible') {
34
+ alert(event.target.visibilityState);
35
+ doc.getElementById('play-sound').play();
36
+ }
37
+ }
38
+
39
+ function handleFocus (event) {
40
+ alert(event.type);
41
+ event.currentTarget.document.getElementById('play-sound').play();
42
+ }
43
+
44
+ if ('visibilityState' in document) {
45
+ document.addEventListener('visibilitychange', handleVisibilitychange, false);
46
+ } else if ('onfocus' in this) {
47
+ addEventListener('focus', handleFocus, false);
48
+ }
49
+ ```
22
50
  Re: kouji20 さん

1

iOS Safari で Audio API を利用する

2016/05/12 22:07

投稿

think49
think49

スコア18194

answer CHANGED
@@ -1,7 +1,22 @@
1
+ ### focus イベントハンドラ
1
2
  `window.onfocus` はいかがでしょうか。
2
3
  (`addEventListener`を使うと上書きされる心配がなくなります。)
3
4
  https://developer.mozilla.org/ja/docs/Web/Events/focus
4
5
 
5
6
  ※音を鳴らす動作は敬遠される場合があるのでユーザが音のOn/Offを設定出来ると良いと思います。
6
7
 
8
+ ### audio要素の API サポート状況
9
+
10
+ iPhone で動作しないとのことですが、`onfocus` を確認する前にaudio要素のAPIサポート状況を確認する必要があると思います。
11
+ `HTMLMediaElement#play` が存在するのか。
12
+
13
+ ```JavaScript
14
+ alert('play' in document.getElementById("play-sound"));
15
+ ```
16
+
17
+ iOS Safari で再生可能な音楽フォーマットを使っているのか。
18
+
19
+ - [HTMLMediaElement - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#Browser_compatibility)
20
+ - [Media formats supported by the HTML audio and video elements - HTML | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats#Browser_compatibility)
21
+
7
- Re: kouji20 さん
22
+ Re: kouji20 さん