페이지 이동경로
  • Docs>
  • Getting Started>
  • JavaScript

Getting Started

JavaScript

This document describes what you should do to integrate the Kakao SDK for JavaScript (hereinafter referred to as 'JavaScript SDK') into your web before leveraging the Kakao APIs.

You can demonstrate or test the functionalities of the JavaScript SDK provided on [Tools].

IMPORTANT

As the new version of the JavaScript SDK has been released. If you are using the Legacy JavaScript SDK, upgrade to a new version by referring to Upgrade v1 to v2.

Set up your app

Before using the JavaScript SDK, you need to set up your application (app) in Kakao Developers.

  1. Create an app.
  2. Register your site domains in [My Application] > [Platform].

Install SDK

You can load the JavaScript SDK into your web page by adding a <script> element. You must specify an SDK version in the path. To find the latest SDK version, see SDK Download.

To strengthen security, we recommend setting the integrity and crossorigin attributes. If integrity is used, you must use the precise integrity value for the SDK version you want to use.

<script src="https://t1.kakaocdn.net/kakao_js_sdk/${VERSION}/kakao.min.js"
  integrity="${INTEGRITY_VALUE}" crossorigin="anonymous"></script>

Initialize SDK

To initialize the JavaScript SDK, add the init() function in your JavaScript file and pass your JavaScript key copied in [My Application] > [App Keys].

Kakao.init('JAVASCRIPT_KEY');
Kakao.isInitialized();

Here is an example of initializing the JavaScript SDK and checking if the initialization is successfully done by calling the isInitialized() function.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Kakao JavaScript SDK</title>
  <script src="https://t1.kakaocdn.net/kakao_js_sdk/${VERSION}/kakao.min.js"
    integrity="${INTEGRITY_VALUE}" crossorigin="anonymous"></script>
  <script>
    // Initialize SDK with JavaScript key for your app.
    Kakao.init('JAVASCRIPT_KEY');

    // Check if the initialization is successfully done.
    console.log(Kakao.isInitialized());
  </script>
</head>
<body></body>
</html>

Supported web browser

The JavaScript SDK supports the most commonly used web browsers. Here are the supported web browsers and versions by platform.

Browser / Platform Android iOS macOS Windows
Chrome* O O O O
Edge* O O O O
Firefox* O O O O
Safari X O O X
Internet Explorer (IE) X X X O**

* JavaScript SDK supports the latest two versions of Chrome, Edge, and Firefox.

** JavaScript SDK supports IE 11 only.

Set up for hybrid app

If you want to use the JavaScript SDK for a web page on a hybrid application (hereinafter referred to as 'hybrid app'), you must develop a WebView as follows to work properly.

The Kakao SDK is intended to make your development much easier. However, when you need to integrate Kakao Login and Kakao Talk sharing into a hybrid app using the JavaScript SDK, you need to proceed the extra jobs as follows due to technological limitation.

  • Run the Kakao Talk application through Custom URL
  • Display a pop-up WebView

Here are the procedures to develop a WebView on the Android and iOS platforms.

For Android

The code snippets below are written in Kotlin.

Add package name

On Android 11 or higher, you must add the package name to the AndroidManifest.xml file to implement the Kakao Login and Kakao Talk sharing features using the JavaScript SDK. Otherwise, Android Framework blocks the API calls.

<manifest package="com.example.sample">
    <queries>
        <package android:name="com.kakao.talk" />
    </queries>
    ...
</manifest>
Run Kakao Talk

To log in with Kakao or send a Kakao Talk sharing message, the JavaScript SDK creates a URL to run Kakao Talk and makes a call. In general, a web browser starts Kakao Talk through the URL. If you do not process the actions described below for WebViews, an error occurs.

Use Intent URI to run an app through a WebView on the Android app. Refer to Android Intents with Chrome for more details.

Create Intent URI for the JavaScript SDK to run Kakao Talk and make a call. Override the WebViewClient#shouldOverrideUrlLoading method in WebView, parse intent and run Activity.

webView = // main WebView

// common settings
webView.settings.run {
    javaScriptEnabled = true
    javaScriptCanOpenWindowsAutomatically = true
    setSupportMultipleWindows(true)
}

webView.webViewClient = object: WebViewClient() {

    override fun shouldOverrideUrlLoading(view: WebView,request: WebResourceRequest): Boolean {
        Log.d(TAG, request.url.toString())

        if (request.url.scheme == "intent") {
            try {
                // Create Intent 
                val intent = Intent.parseUri(request.url.toString(), Intent.URI_INTENT_SCHEME)

                // run an app if there is an executable app.
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                    Log.d(TAG, "ACTIVITY: ${intent.`package`}")
                    return true
                }

                // Load the WebView if there is Fallback URL
                val fallbackUrl = intent.getStringExtra("browser_fallback_url")
                if (fallbackUrl != null) {
                    view.loadUrl(fallbackUrl)
                    Log.d(TAG, "FALLBACK: $fallbackUrl")
                    return true
                }

                Log.e(TAG, "Could not parse anythings")

            } catch (e: URISyntaxException) {
                Log.e(TAG, "Invalid intent request", e)
            }
        }

        // Implement the rest logic for a service.

        return false
    }
}
Display a pop-up WebView

Use a pop-up window to implement some functionalities in the JavaScript SDK for a better user experience. For this, you need to make a WebView created or deleted according to window.open() and window.close() calls.

If you set WebChromeClient for WebView, the following methods are called when a pop-up funcution starts in the JavaScript:

webView = // Main WebView
webViewLayout = // The layout that the WebView is included 

// Common settings 
webView.settings.run {
    javaScriptEnabled = true
    javaScriptCanOpenWindowsAutomatically = true
    setSupportMultipleWindows(true)
}

webView.webChromeClient = object: WebChromeClient() {

    /// ---------- Open pop-up  ----------
    /// - Use a pop-up for Kakao Login in the JavaScript SDK. 
    /// - Must create a seperate WebView when calling window.open() 
    ///
    override fun onCreateWindow(
        view: WebView,
        isDialog: Boolean,
        isUserGesture: Boolean,
        resultMsg: Message
    ): Boolean {

        // Create a WebView 
        var childWebView = WebView(view.context)

        // Set the same WebView as a parent WebView.  
        childWebView.run {
            settings.run {
                javaScriptEnabled = true
                javaScriptCanOpenWindowsAutomatically = true
                setSupportMultipleWindows(true)
            }
            layoutParams = view.layoutParams
            webViewClient = view.webViewClient
            webChromeClient = view.webChromeClient
        }

        // Add a WebView to the layout
        webViewLayout.addView(childWebView)
        // TO DO: It is recommended to manage a seperate WebView
        //       to handle navigation action of users
        //       such as onBackPressed() besides adding a layout.
        //   ex) childWebViewList.add(childWebView)

        // Syncronize between WebViews 
        val transport = resultMsg.obj as WebView.WebViewTransport
        transport.webView = childWebView
        resultMsg.sendToTarget()

        return true
    }

    /// ---------- Close a pop-up  ----------
    /// - Must close the created WebView when window.close() is called. 
    ///
    override fun onCloseWindow(window: WebView) {
        super.onCloseWindow(window)

        // Remove a pop-up from the layout 
        webViewLayout.removeView(window)
        // TO DO: It is recommended to manage a seperate WebView array
        //       to handle navigation action of users
        //       such as onBackPressed() besides adding a layout.
        //   ex) childWebViewList.remove(childWebView)
    }
}

For iOS

The code snippets below are written in Swift.

Run Kakao Talk

To log in with Kakao or send a Kakao Talk sharing message, the JavaScript SDK creates a URL to run Kakao Talk and makes a call.

On iOS devices, an app is launched through Custom URL Schemes or Universal Links. If a Universal Link is invoked, a web browser launches Kakao Talk through the URL. Thus, you do not need to process any particular job to open the URL because the JavsScript SDK supports the Universal Link.

On the other hand, if a Custom URL Scheme is invoked, you must process as follows for a WebView. Otherwise, an error occurs. Kakao Talk only starts when opening the URL on a WebView through the open(_ url:) method.

func webView(_ webView: WKWebView,
             decidePolicyFor navigationAction: WKNavigationAction,
             decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
) {
    print(navigationAction.request.url?.absoluteString ?? "")
    
    // If the Custom URL Scheme is invoked, open(_ url:) is called. 
    if let url = navigationAction.request.url , ["kakaolink"].contains(url.scheme) {

        // If the system can handle the url, Kakao Talk is launched.
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }

        decisionHandler(.cancel)
        return
    }
    
    // Implement the rest logic for your service.


    decisionHandler(.allow)
}
Display a pop-up WebView

Use a pop-up window to implement some functionalities in the JavaScript SDK for a better user experience. For this, you need to make a WebView created or deleted according to window.open() and window.close() calls.

If you set WKUIDelegate for WebView, the following methods are called when a pop-up funcution starts in the JavaScript:

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    // Manage a list of WebViews 
    var webViews = [WKWebView]()

    ...

    /// ---------- Open pop-up  ----------
    /// - Use a pop-up for Kakao Login in the JavaScript SDK. 
    /// - Must create a seperate WebView when calling window.open() 
    ///
    func webView(_ webView: WKWebView,
                 createWebViewWith configuration: WKWebViewConfiguration,
                 for navigationAction: WKNavigationAction,
                 windowFeatures: WKWindowFeatures
    ) -> WKWebView? {
        guard let frame = self.webViews.last?.frame else {
            return nil
        }

        // If creating a WebView and returning the WebView, the WebView becomes a child of the current WebView as a parent
        return createWebView(frame: frame, configuration: configuration)
    }

    /// ---------- Close a pop-up  ----------
    /// - Must close the created WebView when window.close() is called. 
    ///
    func webViewDidClose(_ webView: WKWebView) {
        destroyCurrentWebView()
    }

    // An example of methods to create a WebView 
    func createWebView(frame: CGRect, configuration: WKWebViewConfiguration) -> WKWebView {
        let webView = WKWebView(frame: frame, configuration: configuration)
        
        // Set delegate
        webView.uiDelegate = self
        webView.navigationDelegate = self
                
        // Add to the layout 
        self.view.addSubview(webView)

        // Add to the list of WebViews 
        self.webViews.append(webView)

        // Add other views to optimize for a service environment 

        
        return webView
    }

    // an example of methods to delete a WebView  
    func destroyCurrentWebView() {
        // Remove a WebView from the layout abd list of WebViews
        self.webViews.popLast()?.removeFromSuperview()
    }

}

Upgrade v1 to v2

If you use the Legacy JavaScript SDK (lower version of 2.0.0, hereinafter 'JavaScript SDK v1'), we recommend you to upgrade to the latest version of JavaScript SDK (version 2.0.0 or higher, hereinafter 'JavaScript SDK v2') with this upgrade guide.

Breaking changes

Here are the major changes in the JavaScript SDK v2. To see how to take action for each change, click the corresponding link below:

Change minimum version of Internet Explorer

The minimum supported version of Internet Explorer (IE) is changed to IE 11 in JavaScript SDK v2. Refer to Supported web browser.

If your service must support IE 9 or IE 10, you need to use the JavaScript SDK v1. However, we recommend using the JavaScript SDK v2 because JavaScript SDK v1 may not be supported anymore.

Change script tag used to load JavaScript SDK

To load the JavaScript SDK v2, you must specify the JavaScript SDK version inside the <script> element.

You can also use the integrity attribute for Subresource Integrity (SRI) in JavaScript SDK v2 to strengthen security, which is recommended. If this attribute is set, web browsers only allow the script files that include the hash value that matches the set hash value. Ensure that each SDK version has a different integrity value, and thus you must use the precise integrity value that corresponds to the desired SDK version.

To copy the script tag or the integrity value of the desired SDK version, see SDK Download.

<!-- Before -->
<script src="https://t1.kakaocdn.net/kakao_js_sdk/v1/kakao.min.js"></script>

<!-- After -->
<script src="https://t1.kakaocdn.net/kakao_js_sdk/${VERSION}/kakao.min.js"
  integrity="${INTEGRITY_VALUE}" crossorigin="anonymous"></script>

Replace callback patterns with promise patterns

The functions in the JavaScript SDK v2 return the Promise objects instead of callback parameters such as success, fail, and always.

Thus, you must replace the callback parameters with the Promise.then() and Promise.catch() functions by referring to the following sample snippet and each development guide.

// Before
Kakao.API.request({
  url: '/v2/user/me',
  success: function(response) {
    console.log(response);
  },
  fail: function(error) {
    console.log(error);
  },
});

// After
Kakao.API.request({
  url: '/v2/user/me',
})
  .then(function(response) {
    console.log(response);
  })
  .catch(function(error) {
    console.log(error);
  });

End support for login by presenting popup window

To provide a better service with strengthened security, JavaScript SDK v2 does not provide the associated functions used to obtain an access token in a client-side by presenting popup window in JavaScript SDK v1.

To integrate Kakao Login with the JavaScript SDK v2, use the Kakao.Auth.authorize() function instead.

Feature JavaScript SDK v1 JavaScript SDK v2
Kakao Login Kakao.Auth.login()
Kakao.Auth.createLoginButton()
Kakao.Auth.loginForm()
Kakao.Auth.autoLogin()
Kakao.Auth.authorize()

Change module names and API request URLs

As some service names are changed, the associated modules and API request URLs are changed as follows.

Feature JavaScript SDK v1 JavaScript SDK v2
Kakao Talk Sharing Kakao.Link Kakao.Share
Kakao Talk Channel Kakao.PlusFriend Kakao.Channel
Checking Kakao Talk Channel relationship /v1/api/talk/plusfriends /v1/api/talk/channels

See more

Legacy

IMPORTANT

It is highly recommended to upgrade to the new version of JavaScript SDK as soon as possible because the Legacy SDK may not be supported anymore.