javascriptrangy

How to grab selected text from iframe using rangy?


This is a followup question. I've been trying to grab the selected text from iframe using rangy. The code seems to be working for non-iframe content. As per the rangy's doc, it should work.

Here is the demo: http://jsfiddle.net/codef0rmer/UuJ5G/


Solution

  • The problem in your example is that the iframe's document comes from a different domain from the main document, which means that script running in the main document simply cannot access the document within the iframe. The browser only allows scripting between documents if they come from the same domain.

    If the documents do come from the same domain then you can get the selection using rangy.getIframeSelection():

    http://jsfiddle.net/UuJ5G/42/

    Rangy 1.3 relaxes the restrictions on parameters passed to rangy.getSelection() and rangy.createRange(): both will accept any of a Window, Document or <iframe> element, so you can just pass the iframe into rangy.getSelection():

    http://jsfiddle.net/2d6Bk/56/