我想修改网页中的所有出站链接。我只想在每个URL的末尾附加一个动态字符串。我使用fetch获取此字符串。到目前为止,我已经能够获取和修改URL,但无法附加所获取的字符串。
我的代码
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script>
fetch('https://httpbin.org/encoding/utf8')
.then((response) => {
return response.text();
})
.then((text) => {
document.getElementById("MyFetchedString").innerHTML = text.slice(0, 10);
});
document.addEventListener( "DOMContentLoaded", modify_outbound_links);
function modify_outbound_links(){
anchors = document.getElementsByTagName('a');
for (let i = 0; i < anchors.length; i++) {
let p = anchors[i].href;
if (p.indexOf('example.com') === -1) {
//How do i append the fetchedText?
anchors[i].href = p + (p.indexOf('?') != -1 ? "&" : "?") + 'FetchedText';
}
}
} </script>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Modify all outbound links.<br>
<p><a href="https://google.com/">Google.com</a></p>
<p><a href="https://yahoo.com/">Yahoo.com</a></p>
<p><a href="https://example.com/">mydomain.com</a></p>
<p id="MyFetchedString"></p>
</body>
[请帮助我将收到的字符串附加到每个出站URL。我的主要挑战是此JavaScript行: anchors [i] .href = p +(p.indexOf('?')!= -1?“&”:“?”)+'FetchedText我如何在这里附加?”;
[我认为您正在寻找的是这样的东西,我注意到您从API中删除了旧链接,但是如果您需要它与代码一起使用,我会把它放回原处。
document.addEventListener( "DOMContentLoaded", modify_outbound_links);
function modify_outbound_links(){
fetch('https://api.exchangeratesapi.io/latest?symbols=USD,GBP')
.then((response) => {
return response.json();
})
.then((json) => {
anchors = document.getElementsByTagName('a');
for (let i = 0; i < anchors.length; i++) {
let p = anchors[i].href;
if (p.indexOf('example.com') === -1) {
//How do i append the fetchedText?
anchors[i].href = p + (p.indexOf('?') != -1 ? "&" : "?") + 'FetchedText&' + 'USD='+json['rates']['USD'] + '&GBP=' + json['rates']['GBP'];
}
}
document.getElementById("MyFetchedString").innerHTML = text.slice(0, 10);
});
}
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script>
</script>
</head>
<body>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
Modify all outbound links.<br>
<p><a href="https://google.com/">Google.com</a></p>
<p><a href="https://yahoo.com/">Yahoo.com</a></p>
<p><a href="https://example.com/">mydomain.com</a></p>
<p id="MyFetchedString"></p>
</body>