Search code examples
javascripthtmlnavigator

web share API is not working for images saved on server


I am trying to use navigator.share option for my ecommerce website. I am able to send title,url and text but images are not getting attach. Please refer the code below

<html>


<body>
    <div>

        <div>
            <button class="share-btn" id="shareFilesButton">Share Files</button>
        </div>
    </div>
    
    <script>
     
    const shareBtn = document.querySelector('.share-btn');

    shareBtn.addEventListener('click', () => {
    
    // var file = new File([blob], "img1.jpeg", {type: 'image/jpeg'});
    // var filesArray = [file];
   if(navigator.canShare) {
    navigator.share({
      title: 'My awesome post!',
      text: 'This post may or may not contain the answer to the universe',
      url: window.location.href,
        files: ['img1.jpeg']
    }).then(() => {
      console.log('Thanks for sharing!');
    })
    .catch(err => {
      console.log(`Couldn't share because of`, err.message);
    });
  } else {
    console.log('web share not supported');
  }
});
</script>
</body>


</html>

In above example i am trying to send image which is already share on server. Also few places i am getting files: as key and few places its file to send the image. I have tried both but none of them is working.


Solution

  • I have found the answer.

    if ('canShare' in navigator) {
      const share = async function(shareimg, shareurl, sharetitle, sharetext) {
        try {
          const response = await fetch(shareimg);
          const blob = await response.blob();
          const file = new File([blob], 'rick.jpg', {type: blob.type});
    
          await navigator.share({
            url: shareurl,
            title: sharetitle,
            text: sharetext,
            files: [file]
          });
        } catch (err) {
          console.log(err.name, err.message);
        }
      };
     
        document.querySelectorAll('.share-btn').forEach(item => {
      item.addEventListener('click', e => {
           str =   e.target.getAttribute('share');
        //   console.log(e.target.getAttribute('share'));
          str_array = str.split(',');
        //   console.log(str_array[1]);
        share(
          str_array[1],
          str_array[2],
          str_array[0],
          str_array[3]
        );
      })
    })
    
     
    }
     document.querySelectorAll('.share-btn').forEach(item => {
      item.addEventListener('click', e => {
           str =   e.target.getAttribute('share');
          console.log(e.target.getAttribute('share'));
          str_array = str.split(',');
          console.log(str_array[1]);
        share(
          'https://xtremetechie.com/share/img1.jpeg',
          'https://en.wikipedia.org/wiki/Rick_Astley',
          'Rick Astley',
          'Never gonna give you up!'
        );
      })
    })
    .share-btn {
      /*position: absolute;*/
      /*top: 50%;*/
      /*left: 50%;*/
      /*transform: translate(-50%, -50%);*/
      /*-ms-transform: translate(-50%, -50%);*/
      background-color: #555;
      color: white;
      font-size: 16px;
      /*padding: 12px 24px;*/
      border: none;
      cursor: pointer;
      border-radius: 5px;
      text-align: center;
    }
    
    .container .btn:hover {
      background-color: black;
    }
    .wrapper {
        width:250px;
        height:160px;
        float:left;
        border:1px solid black;
        margin:2px;
        text-align:text;
    }
    <html>
    
    
    <body>
        <div>
            <div class="wrapper">
                <img src="https://xtremetechie.com/share/img2.jpg" width="200px"/><br>
                <button class="share-btn" id="shareFilesButton1" share="Test text1, https://xtremetechie.com/share/img2.jpg, https://xtremetechie.com/share/img2.jpg, Short Description for img1"  >Share </button>
            </div>
            <div class="wrapper">
                <img src="https://xtremetechie.com/share/img1.jpeg"  width="200px" /><br>
                <button class="share-btn" id="shareFilesButton" share="Test text2, https://xtremetechie.com/share/img1.jpeg, https://xtremetechie.com/share/img1.jpeg, Short Description for img2"  >Share</button>
            </div>
    
            <div>
    
               
            </div>
           
    
    
        </div>
    </body>
    </html>