0

I created an API.AI chat bot and used "web demo" integration of it in my html file.I mean API.AI gave me an embedded iframe, something like this:

<iframe id="ifrm"   width="350" height="430" src="https://console.api.ai/api-client/demo/embedded/...."></iframe>

and I used it in my HTML file.

Now I want to get the text of <input> tag, which is inside the above <iframe>.

<input type="text" name="q" id="query" placeholder="Ask something...">

I've tried different ways to get this <input> text. For example:

$('#ifrm').contents().find("#query")

but the result was "undefined". Does anybody know what I should do to have the text of this input tag in my HTML file?

Thanks in advance

mcfish
  • 102
  • 1
  • 10
we.are
  • 409
  • 2
  • 6
  • 15

1 Answers1

0

If the iframe and your page aren't under the same domain, your web browser won't allow you into the iframe. If, however, the two are under the same domain, you can try something similar to the following:

var iframe = document.getElementById("your_iframe_id");
var iframe_contents = iframe.contentDocument.body.innerHTML;
var textbox = iframe_contents.getElementById("input_id");

First, you grab a reference to the iframe. The iframe has a property called contentDocument which is a document holding all the html data. You can grab your input from there.

Edit

If the iframe and the page trying to interact aren't under the same domain, the browser will not allow you to interact. This is for security reasons. Consider how problematic it could be if I could embed any web page in mine so it looked identical, and then just slip in some code to monitor key presses or such.

The ruleset defining all the rules for accessing content from Javascript is called the same-origin policy.

mcfish
  • 102
  • 1
  • 10
  • Thanks a lot,but they are not under the same domain.iframe is under API.AI domain while my html file is not. So I'v got this error using your above code : TypeError: iframe.contentDocument is null. Is there any way to do this work in different domains? – we.are Oct 06 '17 at 12:41
  • For security reasons, no. I'll update my answer to explain that too. – mcfish Oct 06 '17 at 20:53