JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div>
<p>This jsfiddle demonstrates selection in a page with a different origin iframe. This text is local; if you select text from this section and then press the button below, you will get an alert with the object returned from window.getSelection().</p>
</div>
<div>
<p>Below is an iframe from a different origin. If you select from within this iframe, you will get an alert telling you that you have a selection of type None. (The only exception to this is when you have a previously existing selection in the document that you didn't deselect; then you get that selection object returned again.)</p>
<iframe id="w3orgiframe" src="https://www.w3.org">My different origin iframe</iframe>
</div>
<div>
<button id="selbutton">Click me to get the current selection</button>
</div>
<div>
<p><b>My question:</b> when I get a selection type of None, how can I tell in Javascript when the user has indeed selected nothing anywhere in the document, as opposed to the case where the user has selected something in the different origin iframe, and thus the selection object is unavailable to me? Is it possible to distinguish between the two cases?</p>
</div>
</body>
CSS
#w3orgiframe {
height: 200px;
width: 80%;
}
#selbutton {
height: 30px;
width: 50%;
margin-top: 10px;
margin-left: 25%;
background: lightgreen;
}
JavaScript
$("#selbutton").on("click", function() {
var sel = window.getSelection();
if ( sel ) {
alert("selection type of " + sel.type + " value is :" + sel + ":" );
}
else {
alert("did not get a selection object back from getSelection");
}
});