iFrame src change event detection?

前端 未结 7 1523
夕颜
夕颜 2020-11-22 08:02

Assuming I have no control over the content in the iframe, is there any way that I can detect a src change in it via the parent page? Some sort of onload maybe?

My l

7条回答
  •  梦谈多话
    2020-11-22 08:35

    Here is the method which is used in Commerce SagePay and in Commerce Paypoint Drupal modules which basically compares document.location.href with the old value by first loading its own iframe, then external one.

    So basically the idea is to load the blank page as a placeholder with its own JS code and hidden form. Then parent JS code will submit that hidden form where its #action points to the external iframe. Once the redirect/submit happens, the JS code which still running on that page can track your document.location.href value changes.

    Here is example JS used in iframe:

    ;(function($) {
      Drupal.behaviors.commercePayPointIFrame = {
        attach: function (context, settings) {
          if (top.location != location) {
            $('html').hide();
            top.location.href = document.location.href;
          }
        }
      }
    })(jQuery);
    

    And here is JS used in parent page:

    ;(function($) {
      /**
       * Automatically submit the hidden form that points to the iframe.
       */
      Drupal.behaviors.commercePayPoint = {
        attach: function (context, settings) {
          $('div.payment-redirect-form form', context).submit();
          $('div.payment-redirect-form #edit-submit', context).hide();
          $('div.payment-redirect-form .checkout-help', context).hide();
        }
      }
    })(jQuery);
    

    Then in temporary blank landing page you need to include the form which will redirect to the external page.

提交回复
热议问题