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

时间:2019-08-04 09:49:24

标签: typescript google-chrome progressive-web-apps navigator

我正在构建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的方式。 我在手机上使用Chrome。以下小提琴可以在我的手机上正常工作,但您需要选择一个文件。 https://jsfiddle.net/ericwilligers/8cpuskqd/

我的共享功能位于一个按钮上,该按钮基本上保留了要共享的文件的链接。

修改

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

TypeError:无法在“导航器”上执行“ canShare”:迭代器getter不可调用。

edit2

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

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

3 个答案:

答案 0 :(得分:1)

如果有人想使用访存来利用异步,则可以像下面这样

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);
  }
}

答案 1 :(得分:0)

这有效

 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);
            });
        }
      });
  }

答案 2 :(得分:0)

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 服务器。 这是分享图像的角度代码示例。 我已将图片存储在assest/img文件夹中,请确保您选择了正确的图片网址进行分享。

}

相关问题