打开一个 URL,然后使用 location.href 或类似的井号

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

有一个带有 "share at whatsapp" 按钮的页面。这将创建并执行一个 URL,例如:

whatsapp://send?text=Some text followed by a link - 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);