You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:54:05