4

I have two iframes in my html page. First i do some text selection in iframe1 and then i move to iframe2 and do some text selection. Problem is when i do text selection in iframe2, highlighted text in iframe1 highlighted background should be removed but this is not happening. How to do this

    <!doctype html>
<html lang="en">
<head>

</head>
<body>
    <iframe src="test.html"></iframe>
    <iframe src="test2.html"></iframe>
</body>
</html>
bharath
  • 845
  • 2
  • 11
  • 23

1 Answers1

0

There may be an easier way to do this. But this was what I came up with. In theory, it should work:

So to clear selection, this is one of the ways:

var clearSelection = function(){ 
     if (window.getSelection) {
         if (window.getSelection().empty) {  // Chrome
             window.getSelection().empty();
         } else if (window.getSelection().removeAllRanges) {  // Firefox
             window.getSelection().removeAllRanges();
         }
     } else if (document.selection) {  // IE?
        document.selection.empty();
     }
}

source: Clear Text Selection with JavaScript

Now we are required to trigger this function for all other iframes except the one that has been made active, when the iframe is clicked, or any text selection has been made in it.

This requires communicating between iframes, which is what complicates it slightly.

Inside each Iframe, put a function that goes like:

//iframe1
document.addEventListener("click", function(){
 window.postMessage({
  "source": "iframe1" 
 }, "*");
})

//iframe2
document.addEventListener("click", function(){
 window.postMessage({
  "source": "iframe2" 
 }, "*");
})

Now subscribe to these messages in the parent frame like this:

//parent frame
var childrenFrames = window.parent.frames;
window.onmessage = function(e){
    if (e.data.source === "iframe1") {
        childrenFrames[1].postMessage("clearSelection", "*");
    }
    if (e.data.source === "iframe2") {
        childrenFrames[0].postMessage("clearSelection", "*");
    }

};

I got the references to the child iframes using window.top.frames (to access the top window object) or window.parent.frames (to access the direct parent window object, while there may be other higher-level ancestors) [ source: How do I postMessage to a sibling iFrame ]

Now, again, in the children frames, subscribe to the message "clearSelection" like so:

//iframe1, iframe2
window.onmessage = function(e){
    if(e.data === "clearSelection"){
        clearSelection();  // the method I mentioned in the beginning
    }
}

There may be a more straightforward way, but this is the best I could do. Hope this helps.

Community
  • 1
  • 1
thereisnospoon
  • 255
  • 2
  • 8