如何自定义原生navigator.share()函数?

问题描述 投票:0回答:1

我正在尝试修改

url
函数的
navigator.share()
参数,以便当有人使用移动浏览器的共享选项共享页面时,我可以自定义 URL。

为什么我需要这个?我有一个 WordPress 网站

www.abcwebsite.com
,它有一个带有子域的动态克隆系统和单个后端站点(不是多站点网络,我们使用插件来管理识别子域并修改某些文本)。例如:
clonea.abcwebsite.com
是主站点的精确副本,除了一些文本元素之外。出于 SEO 目的,我们希望禁用克隆网站被索引,但希望利用克隆网站获得的流量。

我所做的第一步是更改

canonical
元标记以指向根域。后来我发现
navigator.share()
默认使用规范链接,如果找不到则回退到
location.href
。当有人使用浏览器的共享选项共享克隆页面时,它会共享主站点链接而不是克隆链接。这不是一个可行的解决方案。

下一步是完全删除规范的

meta
标签并将其移动到
http
标头。它解决了我们与谷歌的问题。但最近我注意到标头中的规范在 Bing 中不起作用,因此我们的数千个克隆站点现在都出现在 Bing 结果中。

我相信唯一的方法是添加规范的

meta
标签并将其指向主网站,当浏览器的共享选项启动
navigator.share()
时,将克隆站点 url 传递到共享中。

这是我尝试过的方法,但出现了

Maximum call stack size exceeded
错误--

var defaultNavigator = navigator;
function shareThis($args){ return defaultNavigator.share($args); }
navigator.share = function($args){ return shareThis($args); };
navigator.share({ url: "https://www.abcwebsite.com", text: "Test", title: document.title });

这样我就得到了

Failed to execute 'share' on 'Navigator': Illegal invocation

var defaultShare = navigator.share;
function shareThis($args){ return defaultShare($args); }
navigator.share = function($args){ return shareThis($args); };
navigator.share({ url: "https://www.abcwebsite.com", text: "Test", title: document.title });
javascript navigator canonical-link
1个回答
0
投票

我认为

navigator.share
方法是本机浏览器 API,并且期望以
navigator
对象作为其上下文来调用。当我们将它包装在另一个 fn 中时,上下文(
this
)发生变化,并导致错误:“非法调用”。

我会像这样覆盖

navigator.share

// Storing original share method
const originalShare = navigator.share;

// Overriding navigator.share method
navigator.share = function(data) {
  // Modify the data object
  data.url = "https://www.cat-bounce.com";

  // Calling original share method with the modified data
  return originalShare.call(navigator, data);
};

// Use navigator.share as normal but with modifications
navigator.share({
  title: 'My Title',
  text: 'My Text',
  url: 'https://www.clonesite.com'  // This is replaced by override
}).then(() => {
  console.log('Successful share');
}).catch((error) => {
  console.log('Error sharing:', error);
});
© www.soinside.com 2019 - 2024. All rights reserved.