title: Check whether text is highlighted using window.getSelection()
body: <p>I am writing a javascript function that needs to check first whether the user has highlighted / selected some text on the page. I read online that this should work:</p>
  
  <pre><code>if ( typeof window.getSelection() != "undefined" ) {
      var x = window.getSelection().toString();
  }
  else {
      //nothing is selected, so use default value
      var x = "default value";
  }
  </code></pre>
  
  <p>But that did not work because even when nothing is selected, window.getSelection() returns an object.</p>
  
  <pre><code>if ( typeof window.getSelection().toString() !== "" ) {
      var x = window.getSelection().toString();
  }
  else {
      //nothing is selected, so use default value
      var x = "default value";
  }
  </code></pre>
  
  <p>But even though window.getSelection().toString() returns an empty string, it still uses that empty string rather than the default value.</p>
  
  <p>Finally, <code>if ( window.getSelection() )</code> did not work either.</p>
  
  <p>How can I know whether something is selected?</p>