How to Use xterm-addon-web-links (Step-by-Step Guide)

This article introduces how to use the xterm-addon-web-links plugin to implement link recognition and click functionality in xterm.js terminals, including keeping focus on the original tab, using Command key instead of Control key on Mac, and hover tooltips implementation details to improve link interaction experience in xterm.js terminals.

Jul 6, 2023 · 2 min read · 215 Words · -Views -Comments · Programming

The xterm-addon-web-links plugin can be used to implement link recognition and clicking in xterm.js terminal content. Configuration is straightforward, but there are some detail issues. Marking them down here.

Keeping Focus on Original Tab

 term.loadAddon(new WebLinksAddon.WebLinksAddon(
        (event, uri) => {
           if (isMac ? event.metaKey : event.ctrlKey) {
              window.open(uri);
           }
        }));

Browsers have two behaviors for link clicks:

  1. LeftClick directly opens a new tab with focus on the new page
  2. MetaKey+LeftClick opens a new tab but keeps focus on the original page
    • ⌘ on Mac
    • Ctrl on Windows

Since my requirement is to not lose focus when clicking links, I can only add metaKey judgment in the click event to ensure focus doesn’t get lost when users trigger clicks.

Can Ctrl be Used Instead of Meta on Mac?

Ctrl+LeftClick on Mac behaves equivalent to RightClick (right-click menu), so it’s not possible.

Providing Tooltips on Hover

If users don’t know about ⌘+LeftClick for link clicking, we can provide tooltip information when hovering over detected links.

{
      hover: (event, text, location) => {
        console.log(event, text, location);
      }
    }

The second parameter of WebLinksAddon is a configuration parameter that includes a hover callback function. You can get cursor position information from the event, so you can use the position information to create tooltips or similar displays.

Conclusion

That’s it!

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover