LIFF v2 API reference

Client API

Operating environment

For more information about supported operating environments for LIFF v2, see Overview in the LIFF documentation.

Which functions you can use depends on whether the LIFF app is opened in LINE's in-app browser or an external browser. For example, you can't use liff.scanCode() in an external browser. For more information, see the descriptions for each client API.

note LIFF apps are not compatible with OpenChat

For example, retrieving a user's profile information through a LIFF app isn't possible in most cases.

LIFF SDK errors

LIFF SDK errors are returned in LiffError objects.

LiffError object

Property Type Description
code String Code
message String Message. Returned when the defined message exists.

Error details

Code Description
INIT_FAILED Failed to init LIFF SDK.
INVALID_ARGUMENT The argument is invalid.
UNAUTHORIZED
  • The user did not authorize.
  • Try call server api without access token.
FORBIDDEN You don't have enough permission.
INVALID_CONFIG You need to define liffId for LINE login.
INVALID_ID_TOKEN Failed to verify the ID token.
INVALID_ARGUMENT An invalid argument was specified.
THINGS_NO_LINKED_DEVICES No linked device is available.
BLUETOOTH_SETTING_OFF Bluetooth is off.
THINGS_TERMS_NOT_AGREED LINE Things TOS is not agreed.
BLUETOOTH_NO_LOCATION_PERMISSION Location permission is not granted.
BLUETOOTH_LOCATION_DISABLED Location setting is off.
BLUETOOTH_LE_API_UNAVAILABLE The BLE API for LIFF is not available on this device.
BLUETOOTH_CONNECT_FAILED Failed to connect to the device.
BLUETOOTH_ALREADY_CONNECTED The device is already connected.
BLUETOOTH_CONNECTION_LOST No device is connected.
BLUETOOTH_UNSUPPORTED_OPERATION The specified operation is not supported for the specified characteristic.
BLUETOOTH_SERVICE_NOT_FOUND The specified service does not exist in the GATT server.
BLUETOOTH_CHARACTERISTIC_NOT_FOUND The specified characteristic does not exist in the service.

Example error

{
  "code":"INIT_FAILED",
  "message":"Failed to init LIFF SDK"
}

liff.init()

Initializes a LIFF app. You can only call other LIFF SDK methods after calling liff.init(). The LIFF SDK gets access tokens and ID tokens from the LINE platform when you initialize the LIFF app.

note Note

When the LIFF app is started, it immediately opens the endpoint URL specified in Adding a LIFF app to your channel. Call liff.init() before changing the URL. If you call liff.init() after changing the URL, INIT_FAILED will be returned.

Syntax

liff.init(
  config: { liffId: string },
  successCallback?: Function,
  errorCallback?: Function
)

Arguments

Property Type Required Description
config.liffId String Required LIFF app ID. Can be obtained when you add the LIFF app to your channel. For more information, see Adding a LIFF app.
Note: If the user isn't logging in through LINE, you must specify liffId.
successCallback Function Optional Callback to return a data object upon successful initialization of the LIFF app.
Note: Required when a callback is used.
errorCallback Function Optional Callback to return an error object upon failure to initialize the LIFF app.
Note: Required when a callback is used.

Return value

If you omit successCallback and errorCallback, a Promise object is returned.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// Using a Promise object
liff
  .init({
    liffId: "1234567890-abcedfgh" // use own liffId
  })
  .then(() => {
    // Start to use liff's api
  })
  .catch((err: LiffError) => {
    // Error happens during initialization
    console.log(err.code, err.message);
  });

// Using a callback
liff.init({ liffId: "1234567890-abcedfgh" }, successCallback, errorCallback);

liff.getOS()

Gets the environment in which the user is running the LIFF app.

Syntax

liff.getOS()

Arguments

None

Return value

The environment in which the user is running the LIFF app is returned as a string.

Return value Description
ios LINE in-app browser for iOS
android LINE in-app browser for Android
web External browser

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// No sample code available

liff.getLanguage()

Gets the language settings of the environment in which the LIFF app is running.

Syntax

liff.getLanguage()

Arguments

None

Return value

String containing language settings specified in navigator.language in the LIFF app's running environment.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// No sample code available

liff.getVersion()

Gets the version of the LIFF SDK.

Syntax

liff.getVersion()

Arguments

None

Return value

The version of the LIFF SDK is returned as a string.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// No sample code available

liff.isInClient()

Determines whether the LIFF app is running in LINE's in-app browser.

Syntax

liff.isInClient()

Arguments

None

Return value

  • true: Running in LINE browser
  • false: Running in external browser

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// No sample code available

liff.isLoggedIn()

Checks whether the user is logged in.

Syntax

liff.isLoggedIn()

Arguments

None

Return value

  • true: The user is logged in
  • false: The user is not logged in

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
if (liff.isLoggedIn()) {
  // The user can use an API that requires an access token, such as liff.getProfile().
}

liff.login()

Performs the LINE Login process (web login) for the Web app.

note Note

You cannot use liff.login() in LINE's in-app browser.

Syntax

liff.login(
  loginConfig?: {
    redirectUri?: string
  }
)

Arguments

Property Type Required Description
loginConfig.redirectUri String Optional URL to open in the LIFF app after LINE Login. If omitted, the user is redirected to the page that displays when the LIFF app is opened (front page).

Return value

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
if (!liff.isLoggedIn()) {
  liff.login({ redirectUri: "https://localhost:3000" });
}

liff.logout()

Logs out.

Syntax

liff.logout()

Arguments

None

Return value

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
if (liff.isLoggedIn()) {
  liff.logout();
}

liff.getAccessToken()

Gets the current user's access token.

note Note

When the user closes the app, the access token is revoked.

tip Getting an access token
  • If the user starts the LIFF app in LINE's in-app browser, the LIFF SDK will get an access token when you call liff.init()
  • If the user starts the LIFF app in an external browser, the LIFF SDK will get an access token when these steps are satisfied:
    1. You call liff.login().
    2. The user logs in to LINE.
    3. You call liff.init().

Syntax

liff.getAccessToken()

Arguments

None

Return value

Returns the current user's access token as a string.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
const accessToken = liff.getAccessToken();
if (accessToken) {
  fetch("https://api...", {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${accessToken}`
    }
    //...
  });
}

liff.getContext()

Gets the screen type (1-on-1 chat, group, or room) and the ID that identifies the screen from which the LIFF application is launched.

Syntax

liff.getContext()

Arguments

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
const context = liff.getContext();
console.log(context);

Return value

A data object that contains the information necessary to make various API calls.

Property Type Description
type String The type of screen from where the LIFF app was launched. One of:
  • utou:1-on-1 chat
  • room:Room
  • group:Group
  • none:A screen other than a 1-on-1 chat, room, or group. For example, Wallet tab.
viewType String Size of the LIFF app view. One of:
  • compact
  • tall
  • full
For more information, see Adding the LIFF app to a channel.
userId String User ID. Included when the type property is utou, room, or group.
utouId String 1-on-1 chat ID. Included when the type property is utou.
roomId String Room ID. Included when the type property is room.
groupId String Group ID. Included when the type property is group.
note Method may return null object

null is returned in the following cases:

  • The LIFF app is launched on an external browser.
  • The LIFF app is launched on the LINE's in-app browser and LINE login is used.

Example response

{
    "type": "utou",
    "utouId": "UU29e6eb36812f484fd275d41b5af4e760926c516d8c9faa35…b1e8de8fbb6ecb263ee8724e48118565e3368d39778fe648d",
    "userId": "U70e153189a29f1188b045366285346bc",
    "viewType": "full",
    "accessTokenHash": "ArIXhlwQMAZyW7SDHm7L2g"
}

liff.getDecodedIDToken()

Gets the payload of the ID token that's automatically acquired by liff.init(). The payload includes the user display name, profile image URL, and email address.

tip Getting an ID token
  • If the user starts the LIFF app in LINE's in-app browser, the LIFF SDK will get an ID token when you call liff.init()
  • If the user starts the LIFF app in an external browser, the LIFF SDK will get an ID token when these steps are satisfied:
    1. You call liff.login().
    2. The user logs in to LINE.
    3. You call liff.init().

Syntax

liff.getDecodedIDToken()

Arguments

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// No sample code available

Return value

Gets a Promise object containing the ID token payload.

For more information on ID token payloads, see the Payload section of Getting profile information and email address based on ID token in the Integrate LINE Login documentation.

note Returned Promise object containing null

If you didn't select the openid scope when adding the LIFF app to a channel, a Promise object containing null is returned.

Example ID token payload

{
    "iss": "https://access.line.me",
    "sub": "U1234567890abcdef1234567890abcdef ",
    "aud": "1234567890",
    "exp": 1504169092,
    "iat": 1504263657,
    "nonce": "0987654asdf",
    "amr": [
        "pwd"
    ],
    "name": "Taro Line",
    "picture": "https://sample_line.me/aBcdefg123456"
}

liff.getProfile()

Gets the current user's profile.

Syntax

liff.getProfile()

Arguments

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.getProfile()
.then(profile => {
  const name = profile.displayName
})
.catch((err) => {
  console.log('error', err);
});

Return value

Returns a Promise object that contains the user's profile information.

Property Type Description
userId String User ID
displayName String Display name
pictureUrl String Image URL. This property is not returned if it has not been set by the user.
statusMessage String Status message. This property is not returned if it has not been set by the user.

This method internally calls the Social API using axios. For error handling, refer to the axios documentation and Status codes in the Social API reference documentation.

Example user profile information

{
  "userId":"U4af4980629...",
  "displayName":"Brown",
  "pictureUrl":"https://example.com/abcdefghijklmn",
  "statusMessage":"Hello, LINE!"
}

liff.sendMessages()

Sends messages on behalf of the user to the chat screen where the LIFF app is opened. If the LIFF app is opened on a screen other than the chat screen, messages cannot be sent.

note Note

liff.sendMessages() cannot be used with an external browser.

Syntax

liff.sendMessages(
  messages:  Array<Message>
)

Arguments

Property Type Required Description
messages Array of objects Required Message objects
Max: 5
You can send the following types of Messaging API messages:

When messages are sent to a chat that includes a LINE official account, the LINE Platform sends webhook events to the bot server. When image, video, and audio messages are sent using the liff.sendMessages() method, resulting webhook events contain the contentProvider.type property whose value is external. For more information, see Message event in the Messaging API reference.

Return value

There is no return value if the message is sent successfully.

This method internally calls the LINE platform using Fetch. For error handling, refer to the Fetch documentation and Status codes below.

Status codes
Status code Description
400 The message is invalid.
401 Authentication failed.
403 The access token does not have appropriate permissions.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.sendMessages([
  {
    type:'text',
    text:'Hello, World!'
  }
])
.then(() => {
  console.log('message sent');
})
.catch((err) => {
  console.log('error', err);
});

liff.openWindow()

Opens the specified URL in the in-app browser of LINE or external browser.

Syntax

liff.openWindow(params)

Arguments

params object
Property Type Required Description
url String Required URL. Specify the absolute path to the URL.
external Boolean Optional Whether to open the URL in an external browser. Specify one of the following values: The default value is false.
  • true: Opens the URL in an external browser.
  • false: Opens the URL in the in-app browser of LINE.

Return value

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.openWindow({
  url: "https://line.me",
  external: true
});

liff.scanCode()

Starts LINE's QR code reader and gets the string read by the user. To start the QR code reader, grant ScanQR permission to the LIFF app in the LINE Developers Console.

note Not available on LINE for iOS v9.19.0 or later

Due to a technical issue, liff.scanCode() has been suspended on LINE for iOS v9.19.0 and later.

note Note

You cannot use liff.scanCode() in an external browser.

Syntax

liff.scanCode()

Arguments

None

Return value

A Promise object containing the string read by LINE's QR code reader is returned.

Property Type Description
value String String read by the QR code reader

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.scanCode().then(result => {
  // result = { value: '' }
});

liff.closeWindow()

Closes the LIFF app.

Syntax

liff.closeWindow()

Arguments

None

Return value

None

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.closeWindow();

liff.initPlugins()

Enable the plugins.

For example, if you enable the Bluetooth plugin, you can use the client API (liff.bluetooth.*) provided by the Bluetooth plugin.

Syntax

liff.initPlugins(pluginList: Array<String>): Promise<void>

Arguments

Property Type Required Description
pluginNames Array of String Required Plugin name. Specify one of the following values:
  • bluetooth

Return value

There is no return value if the plugin is enabled successfully.

If you fail to enable the plugins, a Promise object containing the error information is returned.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.initPlugins(['bluetooth']).then(() => {
    liffCheckAvailablityAndDo(() => liffRequestDevice());
}).catch(error => {
    console.log(error);
});

liff.bluetooth.getAvailability()

note Not available on LINE for iOS v9.19.0 or later

Due to a technical issue, liff.bluetooth.getAvailability() has been suspended on LINE for iOS v9.19.0 and later.

Check if the Bluetooth plugin can be used. Call this method to check the following conditions:

  • Bluetooth support for the LIFF app added to your channel is enabled

    Note: You must enable the Bluetooth® Low Energy function of the LIFF app added to your channel to initialize the Bluetooth plugin.

  • Smartphone has Bluetooth enabled

  • User has accepted the LINE Things Terms of Use

  • If using LINE on Android, user has granted permission to use smartphone location information

Note: Enable the Bluetooth plugin by using liff.initPlugins() beforehand.

Syntax

liff.bluetooth.getAvailability(): Promise<Boolean>

Arguments

None

Return value

A Promise object is returned. The Promise object contains a Boolean object indicating whether or not the Bluetooth plugin can be used.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
liff.bluetooth.getAvailability().then(available => {
    alert('available?' + available);
});

liff.bluetooth.requestDevice()

note Not available on LINE for iOS v9.19.0 or later

Due to a technical issue, liff.bluetooth.requestDevice() has been suspended on LINE for iOS v9.19.0 and later.

Scans the linked device, and acquires the information.

You can use a filter to restrict the devices that receive the advertisement packets.

Note: Make sure you first enable the Bluetooth plugin with liff.initPlugins().

Syntax

liff.bluetooth.requestDevice(options?: RequestDeviceOptions): Promise<BluetoothDevice>;

Arguments

Property Type Required Description
options Object Optional RequestDeviceOptionsobject expressing the filter. Omit to retrieve advertisement packets from all devices.
Data object
RequestDeviceOptions object
Property Type Required Description
filters Array of Object Required Array of the LINEBluetoothRequestDeviceFilter object
LINEBluetoothRequestDeviceFilter object
Property Type Required Description
deviceId String Required Device ID of the device that receives the advertisement packet

Return value

A Promise object is returned. The Promise object contains the BluetoothDeviceobject indicating information about the devices.

Data object
BluetoothDevice object
Property Type Required Description
id String Required Device ID
name String Optional device name
gatt Object Optional BluetoothRemoteGATTServer object
watchingAdvertisements Boolean Required Monitoring status of advertisement packet (*)
Method Return value Description
watchAdvertisements Promise <void> Starts the reception of the advertisement packet. (*)
unwatchAdvertisements void Stops the reception of the advertisement packet. (*)
addEventListener void Registers the event listener. You can register the event listener in advertisementreceived event(*) and gattserverdisconnected event.
removeEventListener void Deletes the already-registered event listener. You can delete the event listener registered in advertisementreceived event(*) and gattserverdisconnected event.

(*) These functions are implemented on experiment basis. These functions may be changed or stopped without prior notice.

BluetoothRemoteGATTServer object

To communicate with devices, use the BluetoothRemoteGATTServer object that expresses the GATT server (Generic Attribute Profile server).

If Promise is resolved after executing liff.bluetooth.requestDevice(), then BluetoothRemoteGATTServer can be accessed from the gatt property of the BluetoothDevice object.

Property Type Required Description
device Object Required BluetoothDevice object
connected Boolean Required true if connected. false if not connected
Method Return value Description
connect Promise <BluetoothRemoteGATTService> Connects with the device.
disconnect void Disconnects from the GATT server of the device.
getPrimaryService( serviceUUID: string ) Promise <BluetoothRemoteGATTService> Acquires the primary service of the GATT server. Specify a 128-bit UUID in the serviceUUID.
Note: This method does not verify the UUID. The UUID is verified when the characteristics are read or written, and when a notification is started or stopped.
BluetoothRemoteGATTService object

The BluetoothRemoteGATTService object is used to acquire the characteristics.

Property Type Required Description
device Object Required BluetoothDevice object
uuid String Required GATT Service UUID
Method Return value Description
getCharacteristic( characteristicUUID: string ) Promise <BluetoothRemoteGATTCharacteristic> Acquires the characteristics. Specify a 128-bit UUID in the characteristicUUID.
Note: This method does not verify the UUID. The UUID is verified when the characteristics are read or written, and when a notification is started or stopped.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// Don't filter devices receiving advertisement packets
liff.bluetooth.requestDevice().then(device => {
    const listener = (e) => {
      device.removeEventListener('advertisementreceived', listener);
    };
    device.addEventListener('advertisementreceived', listener);

    device.watchAdvertisements();
}).catch(e => {
    console.log(e.code + ':' + e.message);
});

// Filter devices receiving advertisement packets
liff.bluetooth.requestDevice({
        filters: [
            {
                deviceId: 't99137fe055dd4980b40f6ac526da7b0b' // ID of desired bluetooth device (BluetoothDevice.id)
            }
        ]
    }).then(device => {
    const listener = (e) => {
      device.removeEventListener('advertisementreceived', listener);
    };
    device.addEventListener('advertisementreceived', listener);

    device.watchAdvertisements();
}).catch(e => {
    console.log(e.code + ':' + e.message);
});
BluetoothRemoteGATTCharacteristic object

The BluetoothRemoteGATTCharacteristic object is used to read or write the characteristic of the devices, and also to start or stop a notification.

Property Type Required Description
service Object Optional BluetoothRemoteGATTService object
uuid String Required UUID
value Object Optional DataView object
Method Return value Description
readValue Promise <DataView> Reads the value of the characteristic.
writeValue( value: BufferSource ) Promise <void> Writes the value to the characteristic.
startNotifications Promise <BluetoothRemoteGATTCharacteristic> Starts the notification of characteristic change.
stopNotifications Promise <BluetoothRemoteGATTCharacteristic> Stops the notification of characteristic change.
addEventListener void Registers the event listener. You can register the event listener in characteristicvaluechangedevent containing the target property.
removeEventListener void Deletes the already-registered event listener. You can delete the event listener registered in characteristicvaluechanged event.

Note: readValue() method, writeValue() method, startNotifications() method, and stopNotifications() method verify the UUID and properties. If a UUID or property that does not exist is specified, an error occurs.

Events

advertisementreceived event

If an advertisement packet is received, the advertisementreceived event occurs.

Note: The advertisementreceived event is a function that is implemented on experiment basis. This function may be changed or stopped without prior notice.

Property Type Required Description
device Object Required BluetoothDevice object
name String Optional device name
rssi Number Optional RSSI
manufacturerData Object Optional Mapobject. Data in which the Company Identifier Code is mapped to the DataView object.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// Read and write characteristic values from LIFF app
device.gatt
    .connect()
    .then(async () => {
        const service = await device.gatt.getPrimaryService(
            '01234567-0123-0123-0123-012345678901'
        );
        const characteristic = await service.getCharacteristic(
            '01234567-0123-0123-0123-012345678902'
        );
        const value = await characteristic.readValue();

        // suppose we know it is a string, we can decode it
        // here we use TextDecoder for simplicity, you should add a polyfill for compatibility
        const stringValue = new TextDecoder().decode(value);

        // to write string 'liff' into the characteristic
        // here we use TextEncoder for simplicity, you should add a polyfill for compatibility
        await characteristic.writeValue(new TextEncoder().encode('liff'));
    })
    .catch(e => {
        console.log(e.code + ':' + e.message);
    });

// Notify change in characteristic value from LINE Things device
device.gatt.connect().then(async () => {
    const service = await device.gatt.getPrimaryService('01234567-0123-0123-0123-012345678901');
    const characteristic = await service.getCharacteristic('01234567-0123-0123-0123-012345678903');
    characteristic.addEventListener('characteristicvaluechanged', (e) => {
        // suppose we know it is a 16-bit integer value
        console.log('value changed to:' + e.target.value.getInt16();
    });

    await characteristic.startNotifications();
}).catch(e => {
    console.log(e.code + ':' + e.message);
});
gattserverdisconnected event

If the Bluetooth connection is disconnected due to various reasons, the gattserverdisconnected event occurs. Be sure to register the event listener.

characteristicvaluechanged event

If a characteristic is changed, the characteristicvaluechanged event occurs.

liff.bluetooth.referringDevice

note Not available on LINE for iOS v9.19.0 or later

Due to a technical issue, liff.bluetooth.referringDevice has been suspended on LINE for iOS v9.19.0 and later.

When the LIFF app is launched via a device, liff.bluetooth.referringDevice is set to a BluetoothDevice object that indicates device information.

Example request

// No sample code available
// No sample code available
# No sample code available
// No sample code available
// No sample code available
# No sample code available
# No sample code available
// Register event listener for gattserverdisconnected event
liff.bluetooth
    .requestDevice()
    .then(device => {
        device.addEventListener('gattserverdisconnected', () => {
            console.log('device gatt is disconnected');
        });

        window.gatt.connect();
    })
    .catch(e => {
        console.log(e.code + ':' + e.message);
    });

{{ $t("form.question.helpful") }}

{{ $t("form.question.detail") }}

{{ $t("form.question.improve") }}

{{ $t("form.info.start") }}{{ $t("form.info.link") }}{{ $t("form.info.end") }}


{{ $t("form.result.success") }}
{{ $t("form.result.error") }}
{{ $t("form.result.errorLink") }}