1

I'm trying to use pure Javascript (no jQuery) to loop through each iframe on a page, then check to see if any of the iframes contain highlighted (selected) text. Then display an alert showing the highlighted text. The kicker is... the ID's of the iframes will not be known ahead of time. Hence the need to loop through each iframe. FYI - the iframes are all on the same domain, so no cross-domain issues here.

I think my code is pretty close to what I need, but no cigar so far.

On page load, I am doing this...

var iframes = document.getElementsByTagName('iframe');
for (var i = 0; i < iframes.length; i++) {
    iframes[i].contentWindow.document.onmouseup = function() { 
        var iframeSelection = iframes[i].contentWindow.document.getSelection(); 
        if (iframeSelection.toString().length > 0) { alert(iframeSelection); }
    }
}

Also... for this particular project, it only needs to work in Chrome.

Thanks!

  • Try it without "contentWindow": EX var iframeSelection = iframes[i].document.getSelection(); Also, i believe you need to run getSelection on "window" instead of document. – Bioto May 22 '15 at 22:39
  • Thanks, but that's not the issue, because I've already (successfully) tested getting the selected text inside a *single* iframe by using getElementById (while using contentWindow, document, etc.). Just can't figure out how to do this when there's _multiple_ iframes on a page. – JustAnotherCoder May 22 '15 at 22:57

1 Answers1

0

Your iframe and selection code is fine, but you're running into a common JavaScript mistake with for loops - i will always be equal to iframes.length by the time the event handler function is run.

You can avoid that by iterating with Array.prototype.forEach:

var iframes = document.getElementsByTagName('iframe');

[].forEach.call(iframes, function(frame) {
    frame.contentWindow.document.onmouseup = function() { 
      var iframeSelection = frame.contentWindow.getSelection(); 
      if (iframeSelection.toString().length > 0) { alert(iframeSelection); }
  }
});

JSBin

Community
  • 1
  • 1
joews
  • 29,767
  • 10
  • 79
  • 91
  • I never would have figured that out on my own. Much thanks joews... works great! :) – JustAnotherCoder May 22 '15 at 23:10
  • I guess, there are some restrictions now; Cross-Origin Read Blocking (CORB) blocked cross-origin response https://a.et.nytimes.com/track with MIME type application/json – Erdogan Nov 23 '19 at 05:43