Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
45 views
in Technique[技术] by (71.8m points)

javascript - Intercepting anchor href on an SVG

In this sandbox I have a react app example with an iFrame that loads an HTML file and adds a click event listener to it.

The reason is to detect hrefs on click and act accordingly. The HTML also includes an SVG part that I have a problem getting the href with the hostname.

    <div>
      <a href="/items/1234"> Link outside of SVG</a>
    </div>
    <div>
      <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid meet" viewBox="0 0 756 1315">
        <a href="/items/1234" id="huvud">
          <path
            d="M342...14.07Z"
            id="myID"
            fill="#5fe4"
            opacity="50"
          ></path>
        </a>
      </svg>
    </div>

getting the href with the following snippet from MouseEvent

let target = event.target! as HTMLAnchorElement;
    const link = isHyperlink(target) ? target : closestATag(target);
    if (!link) return;
    const theHREF = link.href;

For the fist <a> tag the href is with correct and with hostname (i.g http://localhost:3000/items/1234)

For the <a> tag inside SVG the link.href returns SVGAnimatedString:{baseVal:string, animVal:string} and getting href with link.getAttributeNS('http://www.w3.org/1999/xlink', 'href') does not contain hostname.

question from:https://stackoverflow.com/questions/65922338/intercepting-anchor-href-on-an-svg

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to @Frederic Brüning, my scenario was specific to handle all anchor links.

the xlink:href is depricated

So the a tags in SVG does not need xlink:href="xxx" but only href="xxx"

then the getAttributeNS does not need namespace. getAttributeNS('','href') which returns href (exact string value) for any <a> tag

Then appending origin will fix my problem

theUrl = `${window.location.origin}${link.getAttributeNS('','href')}`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...