3

Can anyone help?

i want to search a string inside an iframe like for example. i have a page called main.html which has an iframe and the contents of the iframe(somesite.com) has a string inside lets say "Home". what i want to happen is to have a script that will search the string "home" inside the iframe "#com" and will alert a message stating the string is found. i want this to be done with jquery and not with server side scripting. please note that somesite.com is an external site and i have no control over it.

main.html:

<html>
<body>
<input type="button" id="search" value="search">
<iframe id="com" src="http://somesite.com"></iframe>
</body>
</html>

somesite.com

<html>
<body>
Home
</body>
</html>

sorry for the bad english, just comment if you have some clarifications.

ChUck_PrOg
  • 331
  • 7
  • 16
  • 1
    [Possible duplicate](http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-an-iframe). – Bart Platak Aug 15 '12 at 06:37
  • 2
    Above reference will give you the answer, but to save some time, given that `somesite.com` is another domain than your own, that will not be possible due to the same-origin policy. – Christofer Eliasson Aug 15 '12 at 06:41
  • @ChristoferEliasson: Don't you mean 'given that `somesite.com` is another domain that you **don't** own' ? :) – Bart Platak Aug 15 '12 at 06:43
  • @norfavrell Ehm, no? Who owns the domain must be irrelevant here right, or do you mean who controlls the domain? If you are in control of the webserver behind that domain, you could implement CORS, and get around the same origin policy, but apart from that, given that it is another domain than your own (the one you host your site on), it will not work. – Christofer Eliasson Aug 15 '12 at 06:51
  • @ChristoferEliasson: Sorry I have actually understood your comment all wrong (it's way past my bedtime you see). Please ignore my previous comment, I have no idea what I was thinking. – Bart Platak Aug 15 '12 at 06:57
  • @norfavrell No worries, we've all been there :) – Christofer Eliasson Aug 15 '12 at 07:11

2 Answers2

6

You could try:

$("#com").contents();

Note that $.contents() can only be performed on an iframe that originates from the same domain due to Same Origin Policy.

So that you could use it to display alert:

if($("#com").contents().text()search("someText")!=-1){
    alert("found");
}
Bart Platak
  • 4,387
  • 5
  • 27
  • 47
0

Something like this may help:

var text = $('#com').contents().find('body').html();
alert(text);

OR

$("body", $("#com").contents()).each(function(){
  if ($(this).text() == "Home") {
    alert('content found');
  }
});
talha2k
  • 24,937
  • 4
  • 62
  • 81