PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 3, 2022

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

 December 03, 2022     getselection, iframe, javascript     No comments   

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 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.



Answered By - Igor Bykov
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing