简体   繁体   English

如何在 JavaScript 中获取“原始”href 内容

[英]How to get "raw" href contents in JavaScript

I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links.我正在尝试编写一个 GreaseMonkey 脚本,我想在其中找到所有相对链接的链接。 It seemed to me that the way to do that would be to match the contents of href against /^https?:/// .在我看来,这样做的方法是将 href 的内容与/^https?:///匹配。

But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http".但是我发现当我访问锚的 href 属性时,它总是被规范化或煮熟成包含“http”的形式。 That is, if the HTML contains:也就是说,如果 HTML 包含:

<a id="rel" href="/relative/link">inner</a>

accessing访问

document.getElementById("rel").href

returns返回

http://example.com/relative/link

How can I access the raw data in the href attribute?如何访问 href 属性中的原始数据?

Alternately, is there a better way to find relative links?或者,是否有更好的方法来查找相对链接?

请尝试使用getAttribute方法

Typical. 典型。 I figured it out myself almost immediately after posting the question. 在发布问题后,我几乎立即想出来了。

instead of: 代替:

anchor.href

use: 使用:

anchor.getAttribute("href")

Of course, it took me longer to type in this answer than it took everyone else to answer it. 当然,输入这个答案花了我更长的时间,而不是其他所有人都回答它。 (Damn, you people are fast.) (该死的,你的人很快。)

Get the link dom and add attributes for same and append the actual link to same.获取链接 dom 并添加相同的属性和 append 的实际链接。

var hrefUrl = 'https://www.google.com/';

const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);

// working

Hope this will work for dynamic links that to append for each dynamic pages under js / ts.希望这适用于 js / ts 下每个动态页面的 append 的动态链接。

Here's a code snippet you could run to test. 这是您可以运行以测试的代码段。

const anchors = document.getElementsByTagName('a');

for (let anchor of anchors) {
  let hrefFullPath = anchor.href;
  let hrefRelativePath = anchor.attributes.href.value;

  console.log('hrefFullPath', hrefFullPath);
  console.log('hrefRelativePath', hrefRelativePath);
}

Let's say, you are at http://localhost:4200 , and this is your document as you have shown in the question. 假设您在http://localhost:4200 ,这是您在问题中显示的文档。

<a id="rel" href="/relative/link">inner</a>

This anchor's attribute value of href is: 此锚点的href属性值为:

document.getElementById('rel').attributes.href.value => /relative/link

And anchor's href value is: 而锚点的href值是:

document.getElementById('rel').href =>  http://localhost:4200/relative/link

I hope it helps. 我希望它有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM