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

求助实现textarea内URL的Facebook分享按钮功能(附代码)

实现Facebook分享功能的解决方案

1. 给「Share Now!」按钮绑定点击事件

修改按钮代码,添加onclick属性关联分享函数:

<button type="button" onclick="shareToFacebook()">Share Now!</button>

2. 编写分享函数

在你的JavaScript代码中新增以下函数,实现获取链接并调用Facebook分享:

function shareToFacebook() {
    // 获取textarea里生成好的链接
    const shareUrl = document.getElementById("title").value;
    // 检查是否有内容,没有就提示用户先生成链接
    if (!shareUrl) {
        alert("请先生成要分享的链接!");
        return;
    }
    // URL编码避免特殊字符问题
    const encodedUrl = encodeURIComponent(shareUrl);
    // 构造Facebook分享链接,打开新窗口
    const facebookShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
    window.open(facebookShareUrl, '_blank', 'width=600,height=400');
}

完整修改后的代码

<p>Enter Your URL here</p>
<input type="url" id="url" placeholder="Paste your link">
<button type="button" onclick="compute(this.form)">Generate Link</button>

<p>Show your link</p>
<textarea rows="5" id="title" readonly="readonly"></textarea>

<button type="button" onclick="myFunction()">Copy Link</button>
<button type="button" onclick="shareToFacebook()">Share Now!</button>

<script>
function compute(form){
    form.title.value=("https://www.youtube.com/channel/"+form.url.value+"?sub_confirmation=1");
}

function ClearForm(form){
    form.title.value="";
}

function ClearData(form){
    form.url.value="";
}

function myFunction() {
    var copyText = document.getElementById("title");
    copyText.select();
    document.execCommand("copy");
    alert("Copied YouTube Link: " + copyText.value);
}

// Facebook分享函数
function shareToFacebook() {
    const shareUrl = document.getElementById("title").value;
    if (!shareUrl) {
        alert("请先生成要分享的链接!");
        return;
    }
    const encodedUrl = encodeURIComponent(shareUrl);
    const facebookShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
    window.open(facebookShareUrl, '_blank', 'width=600,height=400');
}
</script>

关键点说明

  • 先校验textarea内容,避免空链接分享
  • 对分享链接做URL编码,防止特殊字符导致分享失败
  • 使用Facebook官方的分享接口,无需额外引入SDK,兼容性好

内容的提问来源于stack exchange,提问作者Prasad Chinthaka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:36:26