如何共享正确编码的网址?

时间:2020-03-19 13:42:22

标签: javascript

我当前正在开发一个购物应用程序,该应用程序中我想通过url中的GET参数字符串共享用户列表。现在的问题是列表可能包含空格或变音符号。我试图通过使用Javascript函数 encodeURIComponent 来避免错误,这就是我的代码中发生错误的地方。

为进行调试,我在控制台中记录了生成的url。此处,空格和变音符号已正确编码。但是,当我连接url和参数(自登录以来未曾使用过)后,该列表将以其原始格式包含所有非法字符。我错过了真正明显的东西吗?还是我使用的是错误的功能?

这是我的代码:

function shareList() {
    let text = "";
    let boxes = getList(); //returns a list like [..., "Smoothie Purple;selectGetranke;0", "Smoothie Yellow;selectGetranke;0", ...]

    for (let i = 0; i < boxes.length; i++) {
        text += boxes[i] + ",";
    }

    if (text.length > 0) {
        text = text.substring(0, text.length - 1);
    }
    //forms the list into a string: ...,Smoothie Purple;selectGetranke;0,Smoothie Yellow;selectGetranke;0,...

    text = encodeURIComponent(text);
    text = "https://example.com/?lst=" + text;

    console.log(text); //logs https://example.com/?lst=...%2CSmoothie%20Purple%3BselectGetranke%3B0%2CSmoothie%20Yellow%3BselectGetranke%3B0%2C...
    sendWhatsApp(text); //sends the link https://example.com/?lst=...,Smoothie Purple;selectGetranke;0,Smoothie Yellow;selectGetranke;0,...
}

function sendWhatsApp(message) {
    window.location = "whatsapp://send?text=" + message;
}

1 个答案:

答案 0 :(得分:1)

我会错过一些确实很明显的东西吗,还是我使用了错误的功能?

您只完成了一半的工作。

您已将text值编码为在您的 URL中使用。

但是随后您将URL用作另一个URL(whatsapp://send)中的参数值-并且那个值是您未正确进行URL编码的。

window.location = "whatsapp://send?text=" + encodeURIComponent(message);