openharmony 鸿蒙 js-apis-selectionInput-selectionManager

2026-08-25 浏览 (1)

@ohos.selectionInput.selectionManager (Word Selection Management)

This module provides word selection management capabilities, including creating, displaying, moving, hiding, and destroying windows, listening for word selection events, and retrieving the selected text.

NOTE

  • The initial APIs of this module are supported since API version 24. Newly added APIs will be marked with a superscript to indicate their earliest API version.
  • This module is supported only on PCs/2-in-1 devices.
  • APIs of this module can be called only by applications that integrate the ExtensionAbility for word selection.

Modules to Import

import { selectionManager } from '@kit.BasicServicesKit';

selectionManager

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

selectionManager.on('selectionCompleted')

on(type: 'selectionCompleted', callback: Callback<SelectionInfo>): void

Registers a callback to listen for the word selection completion event. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'selectionCompleted'.
callbackCallback<SelectionInfo>YesCallback used to return the word selection information.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600003The application calling the API does not match the application selected in the system settings.

Example

import { selectionManager } from '@kit.BasicServicesKit';

try {
  selectionManager.on('selectionCompleted', (info: selectionManager.SelectionInfo) => {
    console.info(`Enter the callback function.`);
  });
} catch (err) {
  console.error(`Failed to register selectionCompleted callback: ${err.code}, error message: ${err.message}`);
}

selectionManager.off('selectionCompleted')

off(type: 'selectionCompleted', callback?: Callback<SelectionInfo>): void

Unregisters the callback used to listen for the word selection completion event. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'selectionCompleted'.
callbackCallback<SelectionInfo>NoCallback used to return SelectionInfo. If this parameter is not specified, this API unregisters all callbacks for the specified type.

Example

import { selectionManager } from '@kit.BasicServicesKit';

let selectionChangeCallback = (info: selectionManager.SelectionInfo) => {
  console.info(`Enter the callback function.`);
};

selectionManager.on('selectionCompleted', selectionChangeCallback);
try {
  selectionManager.off('selectionCompleted', selectionChangeCallback);
} catch (err) {
  console.error(`Failed to unregister selectionCompleted: ${err.code}, error message: ${err.message}`);
}

getSelectionContent()

getSelectionContent(): Promise<string>

Obtains this selected text content. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Return value

TypeDescription
Promise<string>Promise used to return the content of the selected text.

Error codes

For details about the error codes, see Universal Error Codes and Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600004The interface is called too frequently.
33600005The interface is called at the wrong time.
33600006The current application is prohibited from accessing content.
33600007The length of selected content is out of range.
33600008Getting the selected content times out.

Example

import { selectionManager } from '@kit.BasicServicesKit';

selectionManager.on('selectionCompleted', async (info: selectionManager.SelectionInfo) => {
  try {
    let content = await selectionManager.getSelectionContent();
  } catch (err) {
    console.error(`Failed to get selection content: ${err.code}, error message: ${err.message}`);
  }
});

createPanel

createPanel(ctx: Context, info: PanelInfo): Promise<Panel>

Creates a word selection panel. This API uses a promise to return the result.

Only one main panel and one menu panel can be created for a single word selection application.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
ctxContextYesContext that the current word selection panel depends on.
infoPanelInfoYesInformation about the word selection panel.

Return value

TypeDescription
Promise<Panel>Promise used to return the word selection panel created.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600003The application calling the API does not match the application selected in the system settings.

Example

import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit';
import { Want } from '@kit.AbilityKit';

class SelectionAbilityStub extends rpc.RemoteObject {
  constructor(des: string) {
    super(des);
  }
  onRemoteMessageRequest(
    code: number,
    data: rpc.MessageSequence,
    reply: rpc.MessageSequence,
    options: rpc.MessageOption
  ): boolean|Promise<boolean> {
    return true;
  }
}

class ServiceExtAbility extends SelectionExtensionAbility {
  onConnect(want: Want): rpc.RemoteObject {
    let panelInfo: PanelInfo = {
      panelType: PanelType.MENU_PANEL,
      x: 0,
      y: 0,
      width: 500,
      height: 200
    }
    let selectionPanel: selectionManager.Panel|undefined = undefined;
    selectionManager.createPanel(this.context, panelInfo)
      .then((panel: selectionManager.Panel) => {
        selectionPanel = panel;
        console.info('Succeed in creating panel.');
      }).catch((err: BusinessError) => {
      console.error(`Failed to create panel: ${err.code}, error message: ${err.message}`);
    });
    return new SelectionAbilityStub('remote');
  }
}
export default ServiceExtAbility;

destroyPanel

destroyPanel(panel: Panel): Promise<void>

Destroys the word selection panel. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
panelPanelYesWord selection panel to destroy.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.

Example

import { selectionManager, SelectionExtensionAbility, PanelInfo, PanelType, BusinessError } from '@kit.BasicServicesKit';
import { rpc } from '@kit.IPCKit';
import { Want } from '@kit.AbilityKit';

class SelectionAbilityStub extends rpc.RemoteObject {
  constructor(des: string) {
    super(des);
  }
  onRemoteMessageRequest(
    code: number,
    data: rpc.MessageSequence,
    reply: rpc.MessageSequence,
    options: rpc.MessageOption
  ): boolean|Promise<boolean> {
    return true;
  }
}

class ServiceExtAbility extends SelectionExtensionAbility {
  onConnect(want: Want): rpc.RemoteObject {
    let panelInfo: PanelInfo = {
      panelType: PanelType.MENU_PANEL,
      x: 0,
      y: 0,
      width: 500,
      height: 200
    }
    let selectionPanel: selectionManager.Panel|undefined = undefined;

    selectionManager.createPanel(this.context, panelInfo)
      .then((panel: selectionManager.Panel) => {
        console.info('Succeed in creating panel.');
        selectionPanel = panel;
        try {
          if (selectionPanel) {
            selectionManager.destroyPanel(selectionPanel).then(() => {
              console.info('Succeed in destroying panel.');
            }).catch((err: BusinessError) => {
              console.error(`Failed to destroy panel: ${err.code}, error message: ${err.message}`);
            });
          }
        } catch (err) {
          console.error(`Failed to destroy panel: ${err.code}, error message: ${err.message}`);
        }
      }).catch((err: BusinessError) => {
      console.error(`Failed to create panel: ${err.code}, error message: ${err.message}`);
    });
    return new SelectionAbilityStub('remote');
  }
}
export default ServiceExtAbility;

SelectionInfo

Defines the information of a word selection event.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

NameTypeRead-OnlyOptionalDescription
selectionTypeSelectionTypeNoNoOperation for selecting words.
startDisplayXnumberNoNoX-coordinate of the screen where the word selection starts, in px.
startDisplayYnumberNoNoY-coordinate of the screen where the word selection starts, in px.
endDisplayXnumberNoNoX-coordinate of the screen where the word selection ends, in px.
endDisplayYnumberNoNoY-coordinate of the screen where the word selection ends, in px.
startWindowXnumberNoNoX-coordinate of the window where the word selection starts, in px.
startWindowYnumberNoNoY-coordinate of the window where the word selection starts, in px.
endWindowXnumberNoNoX-coordinate of the window where the word selection ends, in px.
endWindowYnumberNoNoY-coordinate of the window where the word selection ends, in px.
displayIDnumberNoNoID of the screen where the window with selected words is located.
windowIDnumberNoNoID of the window where words are selected.
bundleNamestringNoNoBundle name of the application where words are selected.

Panel

Represents the word selection panel.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

In the following APIs, you must first use createPanel to obtain a Panel instance, and then call the APIs using the obtained instance.

setUiContent

setUiContent(path: string): Promise<void>

Sets the page content for the word selection panel. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
pathstringYesPath of the page content to be set. This path is configured in the resources/base/profile/main_pages.json file of the project in the stage model. The FA model is not supported.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.setUiContent('pages/Index').then(() => {
    console.info('Succeeded in setting the content.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to setUiContent: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to setUiContent: ${err.code}, error message: ${err.message}`);
}

show

show(): Promise<void>

Shows the word selection panel. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

selectionPanel.show().then(() => {
  console.info('Succeeded in showing the panel.');
}).catch((err: BusinessError) => {
  console.error(`Failed to show panel: ${err.code}, error message: ${err.message}`);
});

hide

hide(): Promise<void>

Hides the word selection panel. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

selectionPanel.hide().then(() => {
  console.info('Succeeded in hiding the panel.');
}).catch((err: BusinessError) => {
  console.error(`Failed to hide panel: ${err.code}, error message: ${err.message}`);
});

startMoving

startMoving(): Promise<void>

Moves the word selection panel by dragging. This API uses a promise to return the result. This API must be written in the onTouch callback and the event type must be TouchType.Down.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

RelativeContainer() {
  /* 
   * Page layout content, which should be defined based on your actual needs.
   */
}
.onTouch((event: TouchEvent) => {
  if (event.type === TouchType.Down) {
    if (selectionPanel !== undefined) {
      selectionPanel.startMoving().then(() => {   // selectionPanel is the panel instance created by createPanel.
        console.info('Succeeded in startMoving the panel.');
      }).catch((err: BusinessError) => {
        console.error(`Failed to startMoving panel: ${err.code}, error message: ${err.message}`);
      });
    }
  }
})

moveTo(deprecated)

moveTo(x: number, y: number): Promise<void>

Moves the word selection panel to the specified coordinates on the screen. This API uses a promise to return the result.

NOTE

This API is supported since API version 20 and deprecated since API version 24. You are advised to use moveToGlobalDisplay instead.

System API: This is a system API.

System capability: SystemCapability.SelectionInput.Selection

Parameters

NameTypeMandatoryDescription
xnumberYesValue of the movement along the X axis, in px.
ynumberYesValue of the movement along the Y axis, in px.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.moveTo(200, 200).then(() => {
    console.info('Succeeded in moving the panel.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
}

moveToGlobalDisplay

moveToGlobalDisplay(x: number, y: number): Promise<void>

Moves the word selection panel to the specified coordinates on the screen. This API uses a promise to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
xnumberYesValue of the movement along the X axis, in px.
ynumberYesValue of the movement along the Y axis, in px.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Word Selection Service Error Codes.

IDError Message
33600001Selection service exception.
33600002This selection window has been destroyed.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.moveToGlobalDisplay(200, 200).then(() => {
    console.info('Succeeded in moving the panel.');
  }).catch((err: BusinessError) => {
    console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to move panel: ${err.code}, error message: ${err.message}`);
}

on('destroyed')

on(type: 'destroyed', callback: Callback<void>): void

Registers a callback to listen for the destroy event of the word selection panel. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'destroyed'.
callbackCallback<void>YesCallback function. The return value is null.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.on('destroyed', () => {
    console.info('Panel has been destroyed.');
  });
} catch (err) {
  console.error(`Failed to register destroyed callback: ${err.code}, error message: ${err.message}`);
}

off('destroyed')

off(type: 'destroyed', callback?: Callback<void>): void

Unregisters the callback used to listen for the destroy event of the word selection panel. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'destroyed'.
callbackCallback<void>NoCallback function. The return value is null. If this parameter is not specified, this API unregisters all callbacks for the specified type.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.off('destroyed');
} catch (err) {
  console.error(`Failed to unregister destroyed: ${err.code}, error message: ${err.message}`);
}

on('hidden')

on(type: 'hidden', callback: Callback<void>): void

Registers a callback to listen for the hide event of the word selection panel. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'hidden'.
callbackCallback<void>YesCallback function. The return value is null.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.on('hidden', () => {
    console.info('Panel has been hidden.');
  });
} catch (err) {
  console.error(`Failed to register hidden callback: ${err.code}, error message: ${err.message}`);
}

off('hidden')

off(type: 'hidden', callback?: Callback<void>): void

Unregisters the callback used to listen for the hide event of the word selection panel. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which is 'hidden'.
callbackCallback<void>NoCallback function. The return value is null. If this parameter is not specified, this API unregisters all callbacks for the specified type.

Example

import { selectionManager, BusinessError } from '@kit.BasicServicesKit';

try {
  selectionPanel.off('hidden');
} catch (err) {
  console.error(`Failed to unregister hidden: ${err.code}, error message: ${err.message}`);
}

SelectionType

Enumerates the operations for selecting words.

System capability: SystemCapability.SelectionInput.Selection

Model constraint: This API can be used only in the stage model.

NameValueDescription
MOUSE_MOVE1Move the cursor to select words.
DOUBLE_CLICK2Double-click to select words.
TRIPLE_CLICK3Triple-click to select words.

你可能感兴趣的鸿蒙文章

openharmony 鸿蒙 errorcode-zlib

openharmony 鸿蒙 capi-oh-scan-scan-picturescanprogress

openharmony 鸿蒙 js-apis-screen-lock

openharmony 鸿蒙 capi-os-account-common-h

openharmony 鸿蒙 js-apis-screen-lock-sys

openharmony 鸿蒙 capi-oh-print-print-propertylist

openharmony 鸿蒙 capi-oh-scan

openharmony 鸿蒙 js-apis-system-device

openharmony 鸿蒙 errorcode-intelligentVoice

openharmony 鸿蒙 js-apis-request-sys

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/Guak8exg