Are you familiar with the WebShare API for sharing files?

Hello, I am looking to share images using the new API. When I have an upload form for a file, I can easily share that file with the API. However, I am having trouble trying to share a local file. Here is my attempt:

function sharePage(){
const title     = document.title;
var filesArray  = [];
$.get(baseurl+"images/cover.jpg", { async: false }, function(data) { filesArray.push(data); });
setHashtag('share');
if(navigator.share){
    if(navigator.canShare && navigator.canShare({ files: filesArray })) {
        navigator.share({
            text: 'FILE',
            files: filesArray,
            title: title,
            url: baseurl
        });
    }else{
        navigator.share({
            text: 'NO FILE',
            title: title,
            url: baseurl
        });
    }
}else{
    document.location.href="whatsapp://send?text="+baseurl;
}

EDIT: The problem I'm facing is that I don't know how to implement a server-side file into this script. Something like var file = baseurl+"images/cover.jpg"; I tried using jQuery $.get but it didn't work.

Answer №1

My approach to solving this was to fetch a blob and then create a File object from it. Here's how I did it:

fetch("url_to_fetch_the_file")
  .then(function(response) {
    return response.blob()
  })
  .then(function(blob) {

    var file = new File([blob], "photo.jpg", {type: 'image/jpeg'});
    var fileArray = [file];

    if(navigator.canShare && navigator.canShare({ files: fileArray })) {
      navigator.share({
        text: 'sample_text',
        files: fileArray,
        title: 'sample_title',
        url: 'sample_url'
      });
    }
  });

Answer №2

To implement the same functionality in TypeScript using async/await (assuming that you have already verified the availability of navigator.share):

const fetchedImage = await fetch(imageUrl);
const blobData = await fetchedImage.blob();
const imageFile = new File([blobData], 'image.jpg', { type: 'image/jpeg' });
navigator.share({ text: 'some_text', files: [imageFile] } as ShareData);

Answer №3

I managed to make it work by fetching a blob and creating a File object, following this approach:

fetch("Url-complete-image")
.then(function(response) {
    return response.blob()
  })
.then(function(blob) {

    var file = new File([blob], "Name-of-the-image-with-extension", {type: 'image/jpeg'});
    var filesArray = [file];
    var shareData = { files: filesArray };


    if (navigator.canShare && navigator.canShare(shareData)) {

    // Including title separately since navigator.canShare only accepts files as input
    shareData.title = "Image-Title"

    navigator.share(shareData)
    .then(() => console.log('Sharing was successful.'))
    .catch((error) => console.log('Failed to share', error));

    } else {
    console.log("Your system does not support sharing files.");
    }
 
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bizarre idiosyncrasy in Internet Explorer 7/8 regarding Javascript

Whenever I access my page in IE, the sliding carousel feature malfunctions. Instead of displaying images in a carousel format, they are shown in a list format. It seems like IE is not reading the javascript for the selector and applying the effect as it sh ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

Guidelines for breaking down a produced string within the console.log statement in JavaScript

Seeking clarification on this inquiry. I am a complete novice when it comes to coding. Currently, I have implemented the following do while loop code taken from w3s: var text = ""; var i = 1; do { text += "The number is " + i; i++; ...

The value chosen by the user is not retained by the Select function

Having some trouble with a simple select issue in Angular that is causing my select options to disappear after clicking on them. Here's my code: var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.searchFilt ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Leverage jQuery Dialog to dynamically display data from a table in a user-friendly manner

Currently, I have an instant search table implemented using AngularJS. The table includes an ID column on the far right in a hyperlink format, allowing users to navigate to a specific page linked to their selection for data modification based on the unique ...

I encountered a blank page issue when incorporating ui.bootstrap into my controller within Angular

After attempting to utilize angular bootstrap in my project, I encountered an issue where adding the dependency in my controller and starting the server with grunt serve resulted in a blank page. Take a look at the bower components in the screenshot provid ...

Utilizing JavaScript for manipulating arrays and displaying images

After asking this question previously without a satisfactory solution, I am hoping to provide better clarification. Imagine having an array with 3 items and it lands on 0 - a code is set up to display this in a div. Now, I want the image to be shown righ ...

Mixing colors in THREE.js vertex shader based on height levels

How can I change the color of the mesh to blue only when the height is zero? Currently, I am using a mixture of colors: https://i.sstatic.net/x3s4d.png The issue with this blending method is that it lacks precision. I want the color blue to appear only ...

Transform the character encoding from a non-standard format to UTF-8

Imagine a scenario where there is a page with <meta charset="EUC-KR">, let's call it address-search.foo.com, that allows users to search for an address and sends the data to a specified URL by submitting an HTML form using the POST met ...

unable to view the outcome of an ajax request

I am encountering an issue where I am trying to save an AJAX response to the Post PHP variable and display it on the same page. However, I keep getting a "Notice: Undefined index" error. I believe the problem lies in the success part of the AJAX call. Can ...

Transfer content within <pre> tags to the clipboard using a Vue.js application

I am currently developing a Chrome extension using Vue.js where I aim to copy the content within a pre tag section to the clipboard with the click of a button. By assigning an element ID to the pre tag, I can retrieve the content using a copyToClipboard() ...

Process JSON data from an input using Javascript

I am encountering an obstacle at the final step of my data flow process. Currently, I am in the midst of developing an application that retrieves input from an HTML form field and utilizes Ajax to fetch data relevant to the user's input. Allow me to e ...

What is the best way to include a php file within a div element?

I'm attempting to reload a specific div element only. $("#captcha").html('<?php echo 'abc';?>'); // This is just a test and works fine Since the content of the div is quite large, I attempted: $("#captcha").html('< ...

navigation through sibling views using query-based route in ui-router

Imagine an app with two sides: "left" and "right", each with tabs. The application's URL structure is formatted like this: app/splitscreen/?leftTab=1&rightTab=1 Currently, the HTML template is set up as follows: <!-- splitscreen.tpl.html --& ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

Learn how to integrate Bootstrap with Vue.js TreeView in this tutorial

If you're looking to create a treeview using Vue.js, the code structure would resemble something like this: HTML: <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div ...

Selenium JAR test case encountered a halt when it reached JavaScript commands

While working on a test script for our company using Selenium JUnit, I encountered an issue. The script runs smoothly in my account on the company's network but encounters a roadblock when other employees try to run it, specifically when it reaches th ...

Track the number of button clicks on the website without ever resetting the count

Hello there! I have a fun idea for my website - it will have a button that, when clicked 5 times, displays the number 5. Even if you refresh the page or load it again, it should still show 5 and allow you to keep clicking. I can create a counter for one ...

Converting a JavaScript object into HTML output

I have received the following JSON data: [    {       "fields": {          "url": "http://www.domain_name.co.uk/MP3/SF560783-01-01-01.mp3\n",          "track_name": "Lion City ",          "release_id": 560783,    ...