Skip to content

HyperLink plugin

Jiuqing Song edited this page Mar 7, 2018 · 5 revisions

Go back to Built-in plugins

Hyperlink plugin provides 3 functionalities:

  1. When type or paste a string looks like a hyperlink, it will automatically change this text in to hyperlink (auto link).
  2. Since click on a hyperlink in editor will not bring user to that linked page, this plugin can help show a tooltip on hyperlink with specified text format.
  3. When Ctrl+Click on a hyperlink, open the link in target window

Create plugin instance

Hyperlink is a built-in plugin of RoosterJs. When you create an editor with createEditor() API, this plugin is already included.

To manually create an instance of this plugin, you can use its constructor:

constructor(
    private getTooltipCallback: (href: string) => string = href => href,
    private target?: string
);

Parameters

getTooltipCallback parameter is a callback to get the string for tooltip of a hyperlink. It's default behavior is to return the link href itself. You can replace this behavior by passing in a callback, for example, the code below will cause a tool tip like "Ctrl+Click to open link " to show on hyperlinks:

let hyperLinkPlugin = new HyperLink(href => 'Ctrl+Click to open link' + href);

This tooltip is added temporarily. When we call editor.getContent(), this tooltip will be removed from the result.

If there is already a tooltip (title property) on a hyperlink, the original tooltip will NOT be replaced.

target parameter specifies the target window name when user Ctrl+Click on a hyperlink. If not specified, the default value will be '_blank'.

Event

Where auto link happens, a ContentChangedEvent will be triggered with source equal to ChangeSource.AutoLink, and the new hyperlink node (<A> node) is set to event.data. So that if you'd like to get notified when a new hyperlink generated in your plugin code, you can handle this event like the code below. If you'd also like to know when a new hyperlink is created using createLink() API, you can do similar checking with "contentChangedEvent.source == ChangedSource.CreateLink".

    onPluginEvent(event: PluginEvent) {
        if (event.eventType == PluginEventType.ContentChanged) {
            let contentChangedEvent = <ContentChangedEvent>event;
            
            if (
                contentChangedEvent.source == ChangeSource.AutoLink ||
                contentChangedEvent.source == ChangeSource.CreateLink // This allows you to handle the new link added by createLink() API
            ) {
                let hyperLinkNode = <HTMLAnchorElement>contentChangedEvent.data;

                // Add your code here to do customized handling
            }
        }
    }

For more inforation about ContentChangedEvent, please reference to ContentChangedEvent

More info

Package: roosterjs-editor-plugins

Support from: 6.0.0

Source code: Hyperlink.ts