網站搜尋

google chrome - typescript 中的 navigator.canShare() 權限被拒絕


我正在建立一個 Angular8 PWA,我使用 webshare 來分享文字,這運作得很順利。自 2019 年 5 月起,Chrome 也支援分享檔案。

然而,嘗試在 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。下面的 fiddle 在我的手機上運作正常,但你需要選擇一個檔案。https://jsfiddle.net/ericwilligers/8cpuskqd/

我的分享功能在一個按鈕上,該按鈕基本上保存了要分享的檔案連結。

編輯

如果我將 data.files 從陣列改成物件,我會收到以下錯誤訊息:

TypeError:無法在 'Navigator' 上執行 'canShare':迭代器獲取器不可調用。

編輯2

我建立了一個 CodePen 來重現這個問題:

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

答案#1

這成功了

 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

如果有人想使用 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);
  }
}