如果用户在地址栏中手动输入我们的网址,则不会显示模态



当用户从外部链接(即谷歌搜索结果(访问我们的页面时,我创建的模式会显示,但如果用户通过在地址栏中手动输入我们的URL来进入我们的网站,则会发生错误,模式不会出现

这是我的代码:

const siteUrl = ["website.com"];
const referrer_hostname = new URL(document.referrer).hostname;
if (siteUrl.includes(referrer_hostname)) {
console.log("Don't Show Modal", document.referrer);
} else {
console.log("Show Modal", document.referrer);
$( window ).on('load', function() {
console.log("closure modal firing");
$('#closureModal').modal({
backdrop: 'static',
keyboard: false,
show: true
});
});

CCD_ 1连接到模态的HTML。

错误:(index):123 Uncaught TypeError: Failed to construct 'URL': Invalid URL

在地址栏中输入URL时,document.referrer是一个空字符串"。尝试添加验证:
const referrer_hostname = document.referrer !== "" ? new URL(document.referrer).hostname : "";

这样可以避免TypeError

最新更新