window.getSelection と document.getSelection

window.getSelection()document.getSelection()で返ってくる値が違うって事で調べてみた。

<html>
<head>
<title>getSelection Test</title>
<script type="text/javascript">
function reportSelection(){
    var sels = { normal: getSelection(), win: window.getSelection(), doc: document.getSelection() };
    var div = document.getElementById('div');
    div.innerHTML = '';
    for (var label in sels){
        div.innerHTML += label + ': ' + (typeof sels[label]) + ': `' +sels[label] + "' ";
        div.innerHTML += 'isSelectionObject: ' + (sels[label] instanceof Selection) + '<br/>';
    }
}
</script>
</head>
<body>
<h1>getSelection Test</h1>
<p>aaaaaaaaaaa</p>
<p><button onclick="reportSelection()">click</button></p>
<div id="div"/>
</body>
</html>

結果

normal: object: `aaa' isSelectionObject: true
win: object: `aaa' isSelectionObject: true
doc: string: `aaa' isSelectionObject: false

ということで、window.getSelection(),getSelection()Selectionオブジェクト*1を返し、document.getSelection()は文字列を返すみたいだ。

調べた目的はまた別にあって別にまとめる事にする