Web Share API在Chrome本地可运行 站点上线后失效如何解决?
问题根因
- 分享链接硬编码了本地
localhost域名,线上环境下该地址与实际站点域名不符,违反Web Share API的同源规则,会触发调用失败。 - Web Share API仅允许在安全上下文运行:
localhost属于浏览器特许的安全上下文可正常调用,线上站点必须使用HTTPS协议才能使用该API,若线上为HTTP协议,navigator.share会直接返回undefined,导致分享逻辑无法触发。
修复方案
修改JS代码中硬编码的链接拼接逻辑,改用动态获取当前站点域名的方式生成分享链接,示例代码如下:
$(".share_btn").click(function(e) { const post_id = $(this).attr("id"); // 替换硬编码的localhost,动态获取当前站点域名 const link = window.location.origin + '/hypeup/post/' + post_id + '/'; if (navigator.share) { navigator.share({ title: 'My awesome post!', text: 'This post may or may not contain the answer to the universe', url: link, }).then(() => { console.log('Thanks for sharing!'); }) .catch(err => { console.log(`Couldn't share because of`, err.message); }); } else { console.log('web share not supported'); }});
修改完成后确认线上站点已配置HTTPS证书,全程使用HTTPS协议访问即可。
内容的提问来源于stack exchange,提问作者ritik soni
相关产品推荐
相关产品推荐

