javascript - 如何使用 javascript 在站点中的所有页面/内部链接之间传递 URL 参数?
问题描述
我有一个有两个页面的网站,index.html
并且page2.html
:
索引.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<style type="text/css">
#holder {margin: 20px auto; max-width: 900px;}
</style>
</head>
<body>
<div id="holder">
<h1>Home</h1>
<ul id="menu">
<li><a href="/page2.html">Internal Link</a></li>
<li><a href="https://www.apple.com/" target="_blank">App Store</a>
</li>
</ul>
<h2 id="useApp">Is the user using our app?</h2>
</div>
</body>
</html>
page2.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Page 2</title>
<style type="text/css">
#holder {margin: 20px auto; max-width: 900px;}
</style>
</head>
<body>
<div id="holder">
<h1>Internal Page</h1>
<ul id="menu">
<li><a href="/index.html">Homepage</a></li>
<li><a href="https://www.apple.com/" target="_blank">App Store</a>
</li>
</ul>
<h2 id="useApp">Is the user using our app?</h2>
</div>
</body>
</html>
当用户通过点击 Google 广告登陆 index.html 时,为了启用跟踪广告,将以下参数附加到 URL 的末尾:
?utm_source=google&utm_medium=search&utm_campaign=summer19
出现的一个问题是,当用户导航到站点内的另一个页面时,这些 URL 参数会丢失。我想编写一些 Javascript,当用户点击内部链接时,它们会在用户在网站上的旅程中传递 URL 参数。在外部链接的情况下,它不能包含这些参数。我怎样才能最有效地实现这一点?
非常感谢所有帮助。
解决方案
用于querySelectorAll
查找具有href
属性的所有元素,并从以下位置附加搜索字符串URL(window.location).search
:
var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
var current = link.href;
link.href = current + queryString;
});
编辑
以下是如何使上述内容仅适用于内部链接(我将内部链接分类为以 a/
或.
(相对链接)开头或以http
并包含window.location.hostname
(绝对链接)开头的链接:
var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
if (link.href.startsWith("/") || link.href.startsWith(".") || (link.href.startsWith("http") && link.href.include(window.location.hostname)) {
var current = link.href;
link.href = current + queryString;
}
});
推荐阅读
- python - uwsgi进程占用大量内存
- applescript - AppleScript初学者:突然它不会创建文本文件
- influxdb - 带有空间创建问题的 Influxdb 数据库名称
- amazon-web-services - 限制 AWS Ecs 任务的并发
- node.js - Patternlab Node Mustache - 在 Pattern Lab 上寻找渲染到页面的语法
- charts - 我怎样才能使我的 gnatt highcharts 工具提示成为这种形状
- timeout - LogicApp:发送失败并重试的电子邮件,但有时 2 封电子邮件不是 1。为什么以及如何避免它们?
- sorting - 如何根据字段偏好对elasticsearch结果集进行排序
- sql - 如果 presto/athena 中存在值,有没有办法以编程方式设置标志?
- sql - 绑定 JSON 对象后,雪花合并到更新中不起作用,但在使用简单更新查询进行测试时它可以工作