【问题标题】:How to get IFRAME url change event in ionic 3/4?如何在 ionic 3/4 中获取 IFRAME url 更改事件?
【发布时间】:2020-04-20 08:01:23
【问题描述】:

我的网站是 https://www.example.com/write,我想在 ionic 4 应用程序中将此页面用作 IFRAME,我已经嵌入。但是我想要 IFRAME 的 URL 更改事件,而我在我的应用程序的 iframe 中工作。例如,在 IFRAME 中,我有“发布”按钮,在该按钮上,我正在重定向页面,但我希望在我的 ionic 4 应用程序中出现点击事件,该用户点击了“发布”按钮,或者如果我可以获得新的url,使用它我可以让用户回到应用程序。

这里是示例代码:

<ion-header>
  <ion-toolbar class="gradient-header font">
    <ion-title style="background: transparent;" class="light-back small-text-header">Write Story</ion-title>
    <ion-buttons slot="end">&nbsp;</ion-buttons>
  </ion-toolbar>
</ion-header>


<ion-content>
  <ion-grid fixed style="padding-right:0;">
    <ion-row style="padding-right:0;">
      <ion-col style="padding-right:0;">
        <iframe [src]="urlSafe" style="width: 100%; height: 100vh;border:none;"></iframe>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

这里是 TS 文件:write.page.ts

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { Observable } from "rxjs";

@Component({
  selector: 'app-write',
  templateUrl: './write.page.html',
  styleUrls: ['./write.page.scss'],
})
export class WritePage implements OnInit {
  urlSafe: SafeResourceUrl;
  data:Observable<any>;
  n_link:string = 'https://www.example.com/write';

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.n_link);
  }

}

【问题讨论】:

  • 我很确定这是不可能的,因为您需要从 &lt;iframe&gt; 内部捕获一个事件

标签: javascript angular ionic-framework ionic3 ionic4


【解决方案1】:

您似乎需要使用 window.postMessage 而不是检测 iframe 的 url 更改。正如您在下面看到的,您可以检测来自 iframe 的消息:

// Called sometime after postMessage is called
function receiveMessage(event)
{
  // You can validate the origin of the message for security concerns
  if (event.origin !== "http://example.com:8080")
    return;

  console.log(event.data) //Message sent from an external page of your iframe
}

window.addEventListener("message", receiveMessage, false);

然后从加载到 iframe 的外部页面发送消息:

window.postMessage('Sending a message when Publish button is pressed')

编码愉快!

【讨论】:

    【解决方案2】:

    iFrame 内的事件跟踪在跨域站点中非常受限。

    为了可靠地跟踪单个事件,您应该有权访问您正在访问的页面的内容,然后使用window.postMessage 将事件信息发送回您的父应用

    但是,有一种方法可以检测 iframe 是否已被点击。根据您的用例,这可能对您来说还不够,但如果您正在跟踪简单的交互,这可能就足够了。这是通过跟踪 HTML 中哪个元素处于活动状态来实现的。

    var monitor = setInterval(function(){
        var elem = document.activeElement;
        if(elem && elem.tagName == 'IFRAME'){
            clearInterval(monitor);
            alert('clicked!');
        }
    }, 100);
    

    您可以在此处查看一个工作示例:JSFiddle

    关于here这个话题的长篇大论(别理会接受的回复,已经过时了)

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 1970-01-01
      • 2013-05-09
      • 2020-04-07
      • 2015-01-12
      • 1970-01-01
      • 2020-03-25
      • 2020-01-27
      • 2018-10-06
      相关资源
      最近更新 更多