Issue
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);
});
Solution
When you write window
you reference the window where the code is executed. However, it seems like you want to reference iframe
s 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.
Answered By - Igor Bykov Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.