使用DomSanitationService

时间:2016-07-22 14:21:06

标签: iframe angular components

背景

我正在制定一个过渡策略的概念证明,我们正在调查这些过程将会引发过去的过时战略。将webapp转换为iFrame,同时我们将现有功能转换为Angular。

问题:

我遇到的问题是尝试在iFrame上设置src标记。我试图使用DomSanitationService组件,但我继续得到"不安全的网址"启用此功能时出现错误消息。

代码:

这是我现在拥有的;我尝试在从服务接收URL后擦除组件中的URL。

http.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpService } from './http.service';
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
@Component({
    selector: 'http-frame',
    template: `
        <h1>Angular Frame</h1>
        <iframe [src]='page'></iframe>
  `,
    providers: [
        HttpService,
        DomSanitizationService
    ]
})
export class HttpComponent implements OnInit {
    page:string = '';
    constructor(
        private httpService: HttpService,
        private sanitizer: DomSanitizationService
    ) {};
    ngOnInit(){
        this.httpService.getPage()
            .then(page => {
                console.log(page);
                this.page = this.sanitizer.bypassSecurityTrustResourceUrl(page);
                console.log(this.page);
            });

    }
}

http.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class HttpService {

    private url = "https://www.google.com";
    private retryCount = 2;
    // See the "Take it slow" appendix

    constructor(private http: Http) {}

    getPage(){
        return Promise.resolve(this.url);
    }
}

错误:

  

platform-b​​rowser.umd.js:1900 ORIGINAL EXCEPTION:错误:不安全的值   在资源URL上下文中使用(请参阅http://g.co/ng/security#xss

4 个答案:

答案 0 :(得分:6)

虽然可能有更好的解决方案,但这对我有用。

home.component.ts

import { Component, OnInit } from '@angular/core';
import {GetPageService} from "../services/get_page.service";
import {DomSanitizationService, SafeResourceUrl} from     "@angular/platform-browser";

@Component({
  moduleId: module.id,
  selector: 'sd-home',
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css'],
  directives: [],
  providers: [GetPageService]
})
export class HomeComponent implements OnInit {
  page:SafeResourceUrl;

  constructor(private _gps: GetPageService,private sanitizer: DomSanitizationService) {}

  ngOnInit() {
    this._gps.getPage().subscribe(
        (data)=>{
          this.page = this.sanitizer.bypassSecurityTrustResourceUrl(data);
        }
    )

  }
}

get_page.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx";

@Injectable()
export class GetPageService {

    private url = "http://google.com";
    private retryCount = 2;
    // See the "Take it slow" appendix

    constructor(private _http: Http) {}

    getPage(){
        return this._http.get(this.url)
            .retry(this.retryCount)
            .map((res) => {
                return res.url;
            })
            .catch((err)=>{
            let errMsg = (err.error) ? err.errmsg : 'Unknown Error';
                console.error(errMsg);
                return Observable.throw(errMsg);
            })
    }
}

home.component.html

<iframe [src]='page'></iframe>

答案 1 :(得分:1)

上面的代码对我有用,但是每次点击都没有打开视图,我的代码是as-
这是 view.ts 页面

import {DomSanitizationService} from '@angular/platform-browser';
import { NavController, NavParams } from 'ionic-angular';
import { Component, OnInit } from '@angular/core';
import {GetPageService} from "./get_page.service";
import { Http } from '@angular/http';


@Component({
  templateUrl: 'build/pages/view/view.html',
  providers: [GetPageService]
})

export class ViewPage {

  //url: any;
  page: any;

  constructor(private _gps: GetPageService, private sanitizer: DomSanitizationService, private nav: NavController, navParams: NavParams ) {

    // this.url = navParams.get('url'); 
    // console.log(this.url);
  }

  ngOnInit() {
    this._gps.getPage().subscribe(
        (data)=>{
          this.page = this.sanitizer.bypassSecurityTrustResourceUrl(data);
          //console.log(this.page);
        }
    )
  }
}

接下来是我的服务 get_page.servise.js page-

import { NavController, NavParams } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx";
import { ViewPage } from '../view/view';

@Injectable()
export class GetPageService {

    private url;
    private retryCount = 0;
// Don't know what is use of this count, tried with 1200/ 100/ 12000/ 900 etc. 

    constructor(private _http: Http, navParams: NavParams) {

      this.url = navParams.get('url');
    }

    getPage(){
      return this._http.get(this.url)
        .retry(this.retryCount)
        .map((res) => {
            return res.url;
        })
        .catch((err)=>{
        let errMsg = (err.error) ? err.errmsg : err;
            console.error(errMsg);
            return Observable.throw(errMsg);
        })
    }
}

- 查看此页面

<iframe class= "webPage" [src]='page' width="100%" height="250" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen>

只有一个问题,我的视图会在每个替代点击上加载。 如何解决

答案 2 :(得分:1)

经过大量的谷歌搜索后,我来自己解决了我的问题。

这是我做的工作 -

  1. 删除完整 get_page.servise.js
  2. 评论了此文件的导入

    //从&#34; ./ get_page.service&#34;;

  3. 导入{GetPageService}
  4. 从构造函数中删除 _gps:GetPageService,

  5. 已移除 ngOnInit() 功能

  6. ngOnInit() {
        this._gps.getPage().subscribe(
            (data)=>{
              this.page = this.sanitizer.bypassSecurityTrustResourceUrl(data);
              //console.log(this.page);
            }
        )
      }
    
    1. 最重要的 -

      将构造函数中的所有private as public更改为 -

      构造函数(公共清理程序:DomSanitizationService, public nav:NavController,navParams:NavParams)

    2. 我的控制器是 -

      import {SafeResourceUrl, DomSanitizationService} from '@angular/platform-browser';
      import { NavController, NavParams } from 'ionic-angular';
      import { Component, ViewChild } from '@angular/core';
      import { Http } from '@angular/http';
      import { Slides } from 'ionic-angular';
      
      
      @Component({
        templateUrl: 'build/pages/view/view.html',
      })
      
      export class ViewPage {
      
        //url: any;
        page: any;
        @ViewChild('mySlider') slider: Slides;
      
        constructor( public sanitizer: DomSanitizationService, public nav: NavController, navParams: NavParams ) {
          let url = navParams.get('url');
          this.page = this.sanitizer.bypassSecurityTrustResourceUrl(url);
          // this.url = navParams.get('url'); 
          // console.log(this.url);
        }
      }
      

      查看页面仍与 -

      相同
      <iframe class= "webPage" [src]='page' width="100%" height="250" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen>
      

      希望这对你也有帮助。

答案 3 :(得分:0)

创建简单管道并使用

@Pipe({
 name: 'safeResourceUrl'
})
export class SafeResourceUrlPipe implements PipeTransform {
 constructor(private sanitized: DomSanitizer) {}
  transform(value: string) {
   return this.sanitized.bypassSecurityTrustResourceUrl(value);
  }
}

<iframe [src]="youtubeUrl | safeResourceUrl"></iframe>

注释:在app.module.ts中导入SafeResourceUrlPipe