1.0.2 • Published 4 years ago
@waqasibrahim/webext-locale v1.0.2
A simple utility to easily localize Chrome extensions and WebExtensions.
Installation
Using yarn or npm
yarn add @waqasibrahim/webext-locale
npm install @waqasibrahim/webext-locale
Using <script>
include
Download latest version of webext-locale.js
from dist
folder.
<script src="webext-locale.js"></script>
Usage
Global function
Import the package in your page's entry point. This will register a global function __t
that you can use anywhere in your application.
import '@waqasibrahim/webext-locale';
const extensionName = __t('extName');
const extensionDescription = __t('extDescription', 'A default value');
HTML Localization
<!DOCTYPE html>
<html>
<head>
<title data-localize="extName">My awesome extension</title>
</head>
<body>
<!-- Localize inner text -->
<h1 data-localize="extName">My awesome extension</h1>
<p data-localize="extDescription">My awesome extension's description</p>
<!-- Localize attributes -->
<button data-localize:attr="title:extTooltip" title="Default title">Button</button>
<!-- Multiple attributes -->
<button data-localize:attr="title:closeTooltip,aria-label:closeTooltip" title="Close">Close</button>
</body>
</html>
import { localizeByAttribute } from '@waqasibrahim/webext-locale';
localizeByAttribute();
/*
If you want to use a different attribute then pass the value.
<h1 data-translate="extName">My awesome extension</h1>
<button data-translate:attr="title:extTooltip" title="Default title">Button</button>
*/
localizeByAttribute('data-translate');
Vue.js templates
The plugin will register a function $t
on Vue instance that you can use anywhere in the template.
<template>
<h1>{{ $t('extName') }}</h1>
<button :title="$t('buttonTooltip')">
{{ $t('buttonText') }}
</button>
</template>
import Vue from 'vue';
import { localePlugin } from '@waqasibrahim/webext-locale';
import App from './App.vue';
// Vue.js 2
Vue.use(localePlugin);
new Vue({
el: '#root',
render: (h): VNode => h(App),
});
// Vue.js 3
Vue.createApp(Popup)
.use(localePlugin)
.mount('#root');
API
__t
/**
* Gets the localized string for the specified message using WebExtension i18n API
*
* @param messageName The name of the message, as specified in the messages.json file
* @param defaultValue Default value if message cannot be found in messages.json
* @param substitutions A single or an array of substitution strings
* @returns {string}
*/
function __t(messageName: string, defaultValue?: string, substitutions?: string | string[]) => string;
localizeByAttribute
/**
* Localizes page elements by a specific attribute
*
* @param attributeName
*/
function localizeByAttribute(attributeName?: string): void;