Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get content of iframe with src from other site in MVC app

I want to have a way somehow to get the iframe content when some action is triggered in the iframe window. All the content in the iframe comes from other website. There's a textbox and a button in the iframe and I want to detect when the content will be updated and if there's specific content in the iframe then I need to perform some actions. Currently what I have is this:

<script type="text/javascript">
    $(document).ready(function() {
        var timesRefreshed = 0;
        $('#frame').load(function () {
            if (timesRefreshed == 1) {
                var data = {
                    transactionID : '@Model.OrderId'
                };
                $.ajax({
                    type: "POST",
                    url: '@Url.Action("ConfirmationStep", "Cart")',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(data),
                    dataType: "json",
                    success: function(result) {                       
                    }
            });
            }
            timesRefreshed++;
            if (timesRefreshed == 2) {
                window.location.href = '/Home/PaymentComplete/';
            }           
        });
    });  
</script>

Using this approach doesn't give me a lot of options but simply checks how many times the iframe has been loaded, but for example if the user enters incorrect data the iframe might be loaded but with message saying that the value is not correct.

Now, this piece of code will see that the timesRefreshed equals 2 and it will redirect to the other view. I want to check the actual content of the iframe. I checked the innerHTML property but its empty most probably because the iframe is hosting content from other website.

like image 664
Laziale Avatar asked Mar 28 '14 21:03

Laziale


1 Answers

Try jQuery postMessage. Demo

jQuery postMessage enables simple and easy window.postMessage communication in browsers that support it (FF3, Safari 4, IE8), while falling back to a document.location.hash communication method for all other browsers (IE6, IE7, Opera).

With the addition of the window.postMessage method, JavaScript finally has a fantastic means for cross-domain frame communication. Unfortunately, this method isn’t supported in all browsers.

like image 115
Yasser Shaikh Avatar answered Sep 17 '22 11:09

Yasser Shaikh