SYNCERのロゴ
アイキャッチ画像

closeイベント - 閉じた時に発生

closeイベントは、何らかを閉じた時に発生するイベントです。

概要

名前
close
インターフェイス
Event
仕様書
https://html.spec.whatwg.org/multipage/indices.html#event-close

デモ

WebSocket

WebSocketで通信を切断した時に発生します。

<!-- このコードは編集できます。 -->

<!DOCTYPE html>
<html>
<head>
<style>
	div#result { white-space: pre-wrap ; }
</style>
</head>
<body>
	<p>
		<button id="hoge">接続</button>
		<button id="fuga">切断</button>
	</p>
<hr>
	<div id="result"></div>
<script>
var ws = null ;
var element1 = document.getElementById( "hoge" ) ;
var element2 = document.getElementById( "fuga" ) ;

// 接続
element1.onclick = function () {
	if ( ws && ws.readyState === 1 ) return false ;

	ws = new WebSocket( "wss://socket.syncer.jp/connect" ) ;

	ws.onopen = function() {
		ws.onmessage = function( message ) {
			logUpdate( message.data ) ;
		}

		ws.onclose = function( event ) {
			console.log( event ) ;
			logUpdate( "通信を切断しました。" ) ;
		}
	}
}

// 切断
element2.onclick = function () {
	if ( ws && ws.readyState === 1 ) ws.close() ;
}

var logUpdate = function ( text, noDate ) {
	var resultElement = document.getElementById( "result" ) ;
	resultElement.textContent = text + ( noDate ? "" : "(" + new Date().toLocaleString() + ")" ) + "\n" + resultElement.textContent ;
}
</script>
</body>
</html>
  • Twitterでシェア
  • Facebookでシェア
  • Google+でシェア
  • はてなブックマークでシェア
  • pocketに保存
  • LINEでシェア
更新履歴
2017年10月4日 (水)
コンテンツを公開しました。