LanguageDetector: create() static method
Translator and Language Detector APIs
Translator and Language Detector APIs
The create() static method of the LanguageDetector interface creates a new LanguageDetector instance to detect languages.
[!NOTE] The
create()method requires transient activation, that is, it must be invoked in response to a user action such as a mouse click or button press.
Syntax
LanguageDetector.create(options)
Parameters
options- : An object specifying configuration options for the
LanguageDetector. Possible values include:expectedInputLanguages- : An array of strings specifying the expected languages of the input text, which helps improve the accuracy of the language detection. These should be valid BCP 47 language tags. Defaults to
["en"]. monitor- : A callback function with a CreateMonitor argument that enables monitoring download progress of the AI model.
signal- : An AbortSignal object instance, which allows a
create()operation to be aborted via the associated AbortController. The exact effect is dependent on when AbortController.abort() is called:- If
abort()is called before thecreate()promise resolves, thecreate()operation is canceled. - If
abort()is called after thecreate()promise fulfills, it has the same effect as calling LanguageDetector.destroy(): The resources assigned to the resultingLanguageDetectorinstance are released, and any ongoing and subsequentLanguageDetectormethod calls will reject with anAbortError.
- If
Return value
A Promise that fulfills with a LanguageDetector object instance.
Exceptions
InvalidStateErrorDOMException- : Thrown if the page's Document is not yet active.
NetworkErrorDOMException- : Thrown if:
- The network was not available to download the AI model.
- The user has canceled the AI model download.
NotAllowedErrorDOMException- : Thrown if:
- Usage of the method is blocked by a language-detector Permissions-Policy.
- The user has blocked the AI model download in some way.
- The
create()method wasn't called via transient activation.
NotSupportedErrorDOMException- : Thrown if:
- The language tags specified in
expectedInputLanguagesare invalid, or not supported. - An AI model to support the specified
expectedInputLanguagesis not available.
- The language tags specified in
OperationErrorDOMException- : General-purpose exception thrown if
LanguageDetectorcreation failed for any other reason.
Examples
Basic LanguageDetector creation
const detector = await LanguageDetector.create({
expectedInputLanguages: ["en-US", "zh"],
});