How to clear selection selection inside iframe

I have two iframes in my html page. First I make some text selection in iframe1, and then I go to iframe2 and make some text selection. The problem is that when I make a selection of text in iframe2, the selected text in iframe1 stands out for the background, which should be removed, but this does not happen. How to do it

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

</head>
<body>
    <iframe src="test.html"></iframe>
    <iframe src="test2.html"></iframe>
</body>
</html>
+4
source share
1 answer

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

So, to clear the selection, this is one way:

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 using JavaScript

iframe, , , iframe - .

iframes, .

Iframe , :

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

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

:

//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", "*");
    }

};

iframes, window.top.frames ( ) window.parent.frames ( , ) [: iFrame sibling]

"clearSelection" :

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

, , , . .

0

Source: https://habr.com/ru/post/1618994/


All Articles