How do I check if a textfield in iframe is empty?

2019-06-13 06:23发布

Pretty much the question sums it up. I'm trying to do something similar to Gmail, where if you've entered stuff in a text field then the website will prompt you to to confirm if you want to leave the page.

But what if the text field in question is in an iframe? Obviously I can assign the iframe an id, but is there any javascript command or something that can check if a field in an iframe is empty or not? Is this even possible?

Edit: The iframe source and page the iframe is embedded in are from the same domain.

3条回答
戒情不戒烟
2楼-- · 2019-06-13 07:09
var value = document.getElementById('iframeID').contentDocument
                    .getElementById('theTextBoxId').value;

And yes, it's possible, you just need to get access to the <iframe> document with contentDocument.

From the DOM iframe element, scripts can get access to the window object of the included HTML page via the contentWindow property. The contentDocument property refers to the document element inside the iframe (this is equivalent to contentWindow.document), but is not supported by Internet Explorer versions before IE8.

Scripts trying to access a frame's content are subject to the same-origin policy, and cannot access most of the properties in the other window object if it was loaded from a different domain.

MDN

查看更多
Deceive 欺骗
3楼-- · 2019-06-13 07:13

Just set onbeforeunload as you would as if the iframe'd page were the top-level page. If you try to navigate away in the parent frame or the child frame, it will be interrupted by the confirmation.

查看更多
smile是对你的礼貌
4楼-- · 2019-06-13 07:13

Using JQuery you can access the iframe content:

$("#iFrame").contents().find("#text")
查看更多
登录 后发表回答