'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.
Solution 1:[1]
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).
Solution 2:[2]
I had the same issue. When I was debugging my front-end code to check the error in the browser, I faced this error. I just removed my breakpoints in the browser and it works fine now.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Seyed Morteza Mousavi |
