使用 location.href 或类似内容打开一个 URL,后跟一个哈希符号

Open an URL followed by a hash sign using location.href or similar

本文关键字:一个 URL location 符号 哈希 href 使用      更新时间:2023-09-26

有一个带有"在whatsapp上分享"按钮的页面。这将创建并执行如下 URL:

whatsapp://send?text=一些文本后跟一个链接 - http://link_to_this_page #something

问题是浏览器(我现在只用 Chrome 测试过)会自动从哈希符号中删除

我已经尝试了基本的:

var href = 'whatsapp://send?text=Example text - ';
var uri = location.protocol + '//' + location.host + location.pathname + '#gm.';
location.href = href + uri;

我也尝试了location.replace()location.assign()window.open()都没有运气。

所以问题是,我该怎么办?必须使用哈希,因为它告诉目标页面它必须在javascript中做一些事情(这可能需要更多时间才能更改)。

您应该对查询字符串中的任何内容进行编码。

location.href = href + encodeURIComponent(uri);

您可能应该执行以下操作:

var href = 'whatsapp://send?text=';
var text = 'Example text - ';
var uri = location.protocol + '//' + location.host + location.pathname + '#gm.';
location.href = href + encodeURIComponent(text + uri);