verlager
verlager

Reputation: 876

How can I grab a clicked word in an iframe src with js?

This js allows copying a clicked word in an html element to var "str". But I want to grab a word in an iframe src. I modified the js to target the iframe id #USCF_CUST and grab the clicked word, but it doesn't seem to work. The clicked word is not selected and copied to var "str". Can anyone tell me why?

<div class = "clickable">The rain in Spain falls mainly in the plane.</div>

 $(".clickable").click(function(e) {
 s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
 while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
 range.setStart(node, range.startOffset + 1);
 do {range.setEnd(node, range.endOffset + 1);}
 while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
 str = range.toString().trim(); alert (str);
});

But the above js doesn't work (it does nothing) in this instance:

<iframe id = 'USCF_CUST' src= url_2 ></iframe>

 $("#USCF_CUST").click(function(e) {
 s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
 while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
 range.setStart(node, range.startOffset + 1);
 do {range.setEnd(node, range.endOffset + 1);}
 while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
 str = range.toString().trim(); alert (str);
});

Upvotes: 0

Views: 82

Answers (1)

Igor Bykov
Igor Bykov

Reputation: 2812

When you write window you reference the window where the code is executed. However, it seems like you want to reference iframes window.

Try using contentWindow property of iframe in order to set listeners, getSelection, etc.

It will only work if the origin of both pages is exactly the same.

Upvotes: 1

Related Questions