1

我有带有代码的 test.html 页面(https://gist.github.com/4293833):

<!doctype html>
<html>
<head>
  <script>
  var paymentEventHandler = function (e) {
    console.log(e)
    console.log('payment: ' + JSON.stringify(e.status))
    alert('status: ' + e.status)
  }

  if (document.addEventListener) {
    document.addEventListener('payment', paymentEventHandler)
  } else {
    document.attachEvent('onPayment', paymentEventHandler)
  }
  </script>
</head>
<body>
  <iframe src='/iframe.html'></iframe>
</body>
</html>

和 iframe.html:

<!doctype html>
<html>
    <head>
        <script>
         var event

         if (document.createEvent) {
             event = document.createEvent("HTMLEvents")
             event.initEvent("payment", true, true)
         } else {
             event = document.createEventObject()
             event.eventType = 'payment'
         }

         event.status = 'ok'

         if (window.parent.document.dispatchEvent) {
             window.parent.document.dispatchEvent(event)
         } else {
              window.parent.document.fireEvent('onPayment', event)
         }
        </script>
    </head>
    <body>
    </body>
</html>

代码在 Chrome、Safari、Opera 中有效,但在 Firefox 中我得到了undefined. 为什么?

4

1 回答 1

2

您需要创建自定义事件而不是 htmlevent 并使用 initCustomEvent 进行初始化

html

    <!doctype html>
    <html>
    <head>
      <script>
      var paymentEventHandler = function (e) {
        alert('status: ' + e.detail.status)
      }
    
      if (document.addEventListener) {
        document.addEventListener('payment', paymentEventHandler)
      } else {
        document.attachEvent('onPayment', paymentEventHandler)
      }
      </script>
    </head>
    <body>
      <iframe src='iframe.html'></iframe>
    </body>
    </html>

框架

    <!doctype html>
    <html>
        <head>
            <script>
             var event
    
             if (document.createEvent) {
                 event = document.createEvent("CustomEvent")
                 event.initCustomEvent("payment", true, true, {status:"ok"});
             } else {
                 event = document.createEventObject()
                 event.eventType = 'payment'
             }
    
             if (window.parent.document.dispatchEvent) {
                  console.dir(event);
                 window.parent.document.dispatchEvent(event)
             } else {
                  console.dir(event);
                  window.parent.document.fireEvent('onPayment', event)
             }
            </script>
        </head>
        <body>
        </body>
    </html>
于 2012-12-15T12:09:33.530 回答