Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NotAllowedError: Must be handling a user gesture to perform a share request. navigator.share

I have a simple page with some details whose action I handle via an AJAX request. On success callback of the AJAX call I am trying to trigger navigator.share which gives me an error:

NotAllowedError: Must be handling a user gesture to perform a share request.

Some sample code looks like this:

$("#form-button").on('click', function (event) {
  var ele = $(this);
  event.preventDefault();
  $.ajax({
    // ...
    dataType: "json",
    data: { "foo": "bar" },
    success: function (response) {
      if (navigator.share) {
        navigator.share({
          title: response.text,
          text: response.text,
          url: response.href
        }).then(function () {
          alert('Successful share')
        }).catch(function (error) {
          alert('Error sharing: ' + error);
        });
      }
    },
  });
});

Wuoting from Google developer site states:

... you can only invoke the API in response to a user action, such as a click (e.g., you can't call navigator.share as part of the page load)

It works if I don't have the AJAX call and directly trigger navigator.share under the click event but not when I put it in the AJAX callback. I was hoping that the API would have checked the chain of events.

What alternatives do I have to make it work? I have tried keeping a dummy button and triggering click.

like image 867
Bipul Jain Avatar asked May 14 '19 18:05

Bipul Jain


1 Answers

It seems Chromium shows at the moment a wrong error message for refused data types, for example trying to share a pdf file; sharing a JSON file is not yet allowed either.

It is also possible that other cases where Chromium refuses to "share" give you this same wrong error message. For example in my case I was testing locally (file://...) or using "http" instead of "https".

See this tweet where I found this info: https://twitter.com/daviddalbusco/status/1344641231184396288

And the list of Permitted File Extensions is there: https://docs.google.com/document/d/1tKPkHA5nnJtmh2TgqWmGSREUzXgMUFDL6yMdVZHqUsg/

[Edit] I confirmed that identical code works well on mobile Chrome, and fails on desktop Chrome 89 with following:

  • If I check "Pause on caught exceptions" in debugger, I get the wrong error message: "DOMException: Failed to execute 'share' on 'Navigator': Must be handling a user gesture to perform a share request."
  • If I do not check "Pause on caught exceptions", I get several seconds of "delay", then the promise fails with error "DOMException: Share canceled".

In short my answer would be: "Chrome desktop 89 is not yet ready for Web Share API" (and gives you misleading error messages if you try).

like image 88
kubicle Avatar answered Sep 24 '22 11:09

kubicle