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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 12:23:51

问题


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.


回答1:


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




回答2:


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.




回答3:


Using JQuery you can access the iframe content:

$("#iFrame").contents().find("#text")


来源:https://stackoverflow.com/questions/14330132/how-do-i-check-if-a-textfield-in-iframe-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!