navigator.canShare() 打字稿权限被拒绝

navigator.canShare() in typescript permissions denied

我正在构建一个 Angular8 PWA,我正在使用网络共享来共享文本,效果很好。 自 2019 年 5 月起,Chrome 还支持 sharing of files

但是,尝试在 Typescript 中构建文件共享时 运行 出现以下错误:

NotAllowedError: 权限被拒绝

let navigator: any;
navigator = window.navigator;
const title = "myTitle";
let data = {
  title: title,
  text: text,
  url: url,
  files: []
};
console.log(data);

if (navigator.share) {
  fetch(url)
    .then(res => res.blob()) 
    .then(file => {
      const fileName = data.text + ".mp3";
      const options = { type: "audio/mp3" };
      const newFile = new File([file], fileName, options);
      data.files.push(newFile);
      console.log(data);
//lastModified: 1564912016680
//lastModifiedDate: Sun Aug 04 2019 11:46:56 GMT+0200 (Mitteleuropäische //Sommerzeit) {}
//name: "myName.mp3"
//size: 40643
//type: "audio/mpeg"
//webkitRelativePath: ""
      if (navigator.canShare(data)) {
        navigator
          .share(data)
          .then(() => {})
          .catch(err => {
            console.error("Unsuccessful share " + err.message); //here is am getting the Permissions denied error
          });
      }
    });

我不确定这是我获取文件(看起来不错)还是调用 canShare 的方式。 我在手机 phone 上使用 Chrome。以下 fiddle 与我的 phone 配合使用很好,但您需要 select 一个文件。 https://jsfiddle.net/ericwilligers/8cpuskqd/

我的共享功能是在一个按钮上,该按钮基本上包含要共享的文件的 link。

编辑

如果我将 data.files 从数组更改为对象,我会收到以下错误消息:

TypeError:无法在 'Navigator' 上执行 'canShare':迭代器 getter 不可调用。

edit2

我创建了一个代码笔来重现这个问题:

https://codepen.io/anon/pen/xvXvPZ

这有效

 webshare(url, text) {
    let navigator: any;
    navigator = window.navigator;
    const title = "yourTitle";
    let data = { files: [], text: text, url: url, title: title };
    const options = { type: "audio/mp3" };

    this.http
      .get(url, {
        responseType: "arraybuffer"
      })
      .subscribe(response => {
        console.log(response);

        let blob = new File([response], `${text}.mp3`, options);
        data.files.push(blob);
        console.log(data);
        if (navigator.canShare(data)) {
          navigator
            .share(data)
            .then(() => {})
            .catch(err => {
              console.error("Unsuccessful share " + err);
            });
        }
      });
  }

如果有人想使用 fetch 来利用异步,你可以像下面那样做

const shareNow = async () => {
  let imageResponse = await window.fetch('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png');
  let imageBuffer = await imageResponse.arrayBuffer();
  let fileArray = [new File([imageBuffer], "File Name", {
    type: "image/png",
    lastModified: Date.now()
  })];
  if(window.navigator && window.navigator.canShare && window.navigator.canShare({files: fileArray})){
    navigator.share({
      files: fileArray,
      title: 'Title',
      text: 'Text to show'
    }).then(() => {
      console.log('Thanks for sharing!');
    })
    .catch(console.error);
  }
}

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
const navigator = window.navigator as any;

@Component({
  selector: 'app-image-post',
  templateUrl: './image-post.component.html',
  styleUrls: ['./image-post.component.css']
})
export class ImagePostComponent {

  constructor(private http: HttpClient) {}

  // This method shares the image as apost
  shareNow = async () => {
    console.log("insdie shareNow method....");
    if ('canShare' in navigator) {
      console.log("insdie if condition....");
      let img = 'assets/img/image-post-1.jpg';
      const share = async function () {
        try {
          const response = await fetch(img);
          const blob = await response.blob();
          const file = new File([blob], 'rick.jpg', { type: blob.type });
          await navigator.share({
            url: img,
            title: 'Image',
            text: 'Image',
            files: [file],
          });
          console.log("shared successfully....");
        } catch (err) {
          console.log(err.name, err.message);
        }
      };
      share();
    }
  };
<html>
<head>
 <meta name="description" content="Web Share API demo">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<title>
    Web Share API
</title>

<body>
    <div>
        <div>
            <img src="assets/img/image-post-1.jpg" alt="" style="height: 26rem; width: 26rem;">
        </div>
        <div>
            <button (click)="shareNow()" id="shareFilesButton" style="background-color: blueviolet; color: white;">Share File</button>
        </div>
    </div>
</body>

</html>

使用此代码获取图像共享的共享选项。 请注意 navigation.share 仅适用于 HTTPS,不适用于 HTTP 服务器。 这是 angular 代码共享图片的示例。 我已将图像存储在 assest/img 文件夹中,请确保您 select 更正图像 url 以共享它。

}