### Install Smartcar JS SDK via npm Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Installs the Smartcar JavaScript SDK using npm, a package manager for Node.js. This is the recommended method for integrating the SDK into your project. ```shell npm install @smartcar/auth ``` -------------------------------- ### Open Smartcar Connect Dialog Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Opens the Smartcar Connect authorization dialog in a new window. The dialog guides the user through vehicle selection and authorization. Options can be passed to customize the dialog behavior. ```javascript smartcar.openDialog({ // Options for the dialog, e.g., window size and position }); ``` -------------------------------- ### SPA Redirect Test Setup (JavaScript) Source: https://github.com/smartcar/javascript-sdk/blob/master/test/integration/spa.html Sets up the client and redirect URIs for testing the Smartcar SDK's SPA redirect flow. It defines ports, constructs URIs including the `app_origin` parameter, and configures SDK options for testing security checks and post-message handling. ```javascript const clientPort = 3000; const redirectPort = 4000; const clientUri = `http://localhost:${clientPort}`; const redirectUri = `http://localhost:${redirectPort}/redirect?app_origin=${clientUri}`; const options = { clientId: 'clientId', // required redirectUri, // checked against event origin for security // redirect page to arbitrary url for testing onComplete: () => location.replace('on-post-message-url'), }; const smartcar = new window.Smartcar(options); const encodedState = window.btoa(`{"instanceId":"${smartcar.instanceId}"}`); window.open(`${redirectUri}&state=${encodedState}`); ``` -------------------------------- ### Initialize Smartcar SDK Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Initializes the Smartcar SDK with provided options. Requires clientId and redirectUri. Optional parameters include scopes, completion callback, and mode (test, live, simulated). ```javascript const smartcar = new Smartcar({ clientId: 'YOUR_CLIENT_ID', redirectUri: 'YOUR_REDIRECT_URI', scope: ['read_odometer', 'read_vehicle_info'], onComplete: (err, code, state) => { // Handle completion }, mode: 'test' // or 'live', 'simulated' }); ``` -------------------------------- ### Smartcar Initialization Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Initializes the Smartcar SDK with your application's client ID, redirect URI, and optional configuration settings. ```APIDOC ## new Smartcar(options) ### Description Initializes the Smartcar class with the provided options. ### Method `new Smartcar(options)` ### Parameters #### Request Body - **options** (Object) - Required - The SDK configuration object. - **clientId** (String) - Required - The application's client ID. - **redirectUri** (String) - Required - The registered redirect URI of the application. - **scope** (Array) - Optional - Requested permission scopes. - **onComplete** (Function) - Optional - Callback function executed upon completion of Smartcar Connect. - **testMode** (Boolean) - Optional - Deprecated. Use `mode` instead. Launches Smartcar Connect in test mode. - **mode** (String) - Optional - Determines the mode for Smartcar Connect (e.g., 'test', 'live', 'simulated'). Defaults to 'live'. ### Request Example ```javascript const options = { clientId: 'YOUR_CLIENT_ID', redirectUri: 'YOUR_REDIRECT_URI', scope: ['read_odometer', 'read_vehicle_info'], onComplete: (err, accessObj) => { // Handle completion }, mode: 'test' }; const smartcar = new Smartcar(options); ``` ``` -------------------------------- ### Initialize Smartcar SDK and Trigger Redirect (JavaScript) Source: https://github.com/smartcar/javascript-sdk/blob/master/test/integration/server-side.html This snippet demonstrates how to initialize the Smartcar SDK with specific options, including a redirect URI and an onComplete callback. It then opens a redirect page, which is expected to post a message back to complete the authentication flow. ```javascript const clientPort = 3000; const redirectUri = `http://localhost:${clientPort}`; const options = { clientId: 'clientId', redirectUri: redirectUri, onComplete: () => location.replace('on-post-message-url'), }; const smartcar = new window.Smartcar(options); const encodedState = window.btoa(`{"instanceId":"${smartcar.instanceId}"}`); window.open(`${redirectUri}/redirect?state=${encodedState}`); ``` -------------------------------- ### Initialize Smartcar SDK Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Initializes the Smartcar SDK with your application's client ID, redirect URI, requested scopes, and a callback function to handle the authorization code. The onComplete function is crucial for receiving the authorization code after the user completes the Smartcar Connect flow. ```javascript const smartcar = new Smartcar({ clientId: '', redirectUri: '', scope: ['read_vehicle_info', 'read_odometer'], onComplete: function(err, code) { if (err) { // handle errors from Connect (i.e. user denies access) } // handle the returned code by sending it to your back-end server sendToBackend(code); }, }); ``` -------------------------------- ### Integrate Smartcar SDK via CDN in HTML Source: https://context7.com/smartcar/javascript-sdk/llms.txt Shows how to include the Smartcar SDK in an HTML file using a CDN link, making the `Smartcar` class globally available. It initializes the SDK, handles the connection process, and sends the authorization code to a backend endpoint upon successful completion. This method is suitable for quick integration without a build process. ```html Connect Your Vehicle

Vehicle Connection

``` -------------------------------- ### Smartcar.openDialog Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Opens the Smartcar Connect dialog, allowing users to select their vehicle and grant permissions. ```APIDOC ## smartcar.openDialog(options) ### Description Opens the Smartcar Connect dialog, which handles the OAuth flow for vehicle authorization. ### Method `smartcar.openDialog(options)` ### Parameters #### Request Body - **options** (Object) - Required - Options for opening the dialog. - **url** (String) - Required - The authorization URL generated by `getAuthUrl`. - **onClose** (Function) - Optional - Callback function executed when the dialog is closed. ### Request Example ```javascript const authUrl = smartcar.getAuthUrl({ /* ... */ }); smartcar.openDialog({ url: authUrl, onClose: () => { console.log('Dialog closed'); } }); ``` ``` -------------------------------- ### Initialize Smartcar SDK Constructor Source: https://context7.com/smartcar/javascript-sdk/llms.txt Initializes the Smartcar SDK with application configuration, including client ID, redirect URI, scopes, and mode. It sets up event listeners for authorization codes and handles different modes like 'live', 'test', and 'simulated'. The 'onComplete' callback processes authorization errors or provides the authorization code. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info', 'read_odometer', 'read_location', 'control_security'], mode: 'live', // 'live', 'test', or 'simulated' onComplete: function(error, code, state, virtualKeyUrl) { if (error) { // Handle specific error types if (error.name === 'AccessDenied') { console.error('User denied access:', error.message); } else if (error.name === 'VehicleIncompatible') { console.error('Vehicle not compatible:', error.message); if (error.vehicleInfo) { console.log('Vehicle info:', error.vehicleInfo.make, error.vehicleInfo.year); } } else if (error.name === 'InvalidSubscription') { console.error('Invalid subscription:', error.message); } return; } // Send authorization code to your backend fetch('/api/exchange-code', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, state, virtualKeyUrl }) }); } }); // Initialization for test mode (development) const smartcarTest = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=http://localhost:3000', scope: ['read_vehicle_info', 'read_odometer'], mode: 'test', onComplete: function(error, code) { if (error) return console.error(error); console.log('Test mode authorization code:', code); } }); ``` -------------------------------- ### Configure Smartcar SDK for Server-Side Redirects Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Initializes the Smartcar SDK with a backend redirect URI for traditional OAuth flows. This allows the authorization code to be received on your server instead of the client-side. Ensure the `redirectUri` is registered on the Smartcar dashboard. ```javascript const smartcar = new Smartcar({ clientId: '', redirectUri: '', scope: ['read_vehicle_info', 'read_odometer'], onComplete: function() {} }); ``` -------------------------------- ### Smartcar Constructor Source: https://context7.com/smartcar/javascript-sdk/llms.txt Initializes the Smartcar SDK with your application configuration. It sets up event listeners for receiving authorization codes and validates required options. Supports 'live', 'test', and 'simulated' modes. ```APIDOC ## Smartcar Constructor ### Description Initializes the Smartcar SDK with your application configuration. The constructor sets up event listeners for receiving authorization codes from the Connect popup and validates required options like clientId. Supports three modes: 'live' for production, 'test' for development with test vehicles, and 'simulated' for simulated vehicle data. ### Method `new Smartcar(options)` ### Parameters #### Options Object - **clientId** (string) - Required - Your application's client ID. - **redirectUri** (string) - Required - The URI Smartcar should redirect to after authorization. - **scope** (array of strings) - Required - An array of permissions your application requests (e.g., `['read_vehicle_info']`). - **mode** (string) - Optional - The mode of operation: 'live', 'test', or 'simulated'. Defaults to 'live'. - **onComplete** (function) - Required - A callback function that receives `(error, code, state, virtualKeyUrl)` upon completion of the authorization flow. ### Request Example ```javascript const smartcar = new Smartcar({ clientId: 'YOUR_CLIENT_ID', redirectUri: 'YOUR_REDIRECT_URI', scope: ['read_vehicle_info', 'read_odometer'], mode: 'live', onComplete: function(error, code, state, virtualKeyUrl) { if (error) { console.error('Authorization error:', error); return; } // Send authorization code to your backend fetch('/api/exchange-code', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code, state, virtualKeyUrl }) }); } }); ``` ### Response #### Success Response - **Initialization**: The `Smartcar` object is returned, ready to be used. - **onComplete Callback**: Receives `error` (null on success), `code` (authorization code), `state` (CSRF token), and `virtualKeyUrl` (if applicable). #### Response Example (onComplete callback) ```javascript // Success function(null, 'AUTHORIZATION_CODE', 'STATE_TOKEN', 'VIRTUAL_KEY_URL') // Error function(new Error('AccessDenied'), null, null, null) ``` ``` -------------------------------- ### Smartcar Connect Dialog Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Launches the Smartcar Connect authorization flow in a new window. This method allows users to grant your application access to their vehicle data. ```APIDOC ## POST /smartcar/connect ### Description Launches Smartcar Connect in a new window to initiate the vehicle authorization process. ### Method POST ### Endpoint /smartcar/connect ### Parameters #### Query Parameters - **state** (String) - Optional - Arbitrary state passed to the redirect URI. - **forcePrompt** (Boolean) - Optional - Force the permission approval screen to show on every authentication, even if the user has previously consented to the exact scope of permission. Defaults to `false`. - **vehicleInfo.make** (String) - Optional - Allows users to bypass the car brand selection screen. See [API Reference](https://smartcar.com/docs/api#authorization) for supported makes. - **singleSelect** (Boolean | Object) - Optional - Sets the behavior of the grant dialog. If `true`, limits the user to selecting only one vehicle. If an object with a `vin` property, authorizes only the specified vehicle. See [API reference](https://smartcar.com/docs/api/#connect-match) for more information. - **flags** (Array) - Optional - A list of feature flags for early access. - **windowOptions** (WindowOptions) - Optional - Position and size settings for the popup window. ### Request Example ```json { "state": "a-random-string", "forcePrompt": true, "vehicleInfo": { "make": "TESLA" }, "singleSelect": { "vin": "YOUR_VEHICLE_VIN" }, "flags": ["new-flag"], "windowOptions": { "width": 500, "height": 600, "top": 100, "left": 200 } } ``` ### Response #### Success Response (200) This method does not return a direct success response body as it opens a popup window. The result of the authorization is handled via the redirect URI. ``` -------------------------------- ### Open Smartcar Connect Dialog Directly Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Launches the Smartcar Connect authorization dialog programmatically without requiring a specific HTML element click. This offers flexibility in controlling when and how the Connect flow is initiated. ```javascript smartcar.openDialog(); ``` -------------------------------- ### Handle Server-Side Redirects with Smartcar SDK (JavaScript) Source: https://context7.com/smartcar/javascript-sdk/llms.txt Initialize the Smartcar SDK on the frontend with your backend redirect URI. The backend route then receives the authorization code, exchanges it for tokens, and renders a page with the Smartcar redirect helper script to close the popup. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://myapp.com/auth/smartcar/callback', scope: ['read_vehicle_info', 'read_odometer'], onComplete: function() { console.log('Connect flow completed'); } }); smartcar.addClickHandler({ id: 'connect-btn', state: 'user-abc123' }); // Backend route (Express.js example) at /auth/smartcar/callback: // app.get('/auth/smartcar/callback', (req, res) => { // const { code, error, error_description, state } = req.query; // // if (error) { // return res.render('connect-result', { error: error_description }); // } // // res.send(` // // // //

Connecting your vehicle...

// // // // `); // }); ``` -------------------------------- ### WindowOptions Object Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md An object used to define the position and size settings for the Smartcar Connect popup window. ```APIDOC ## WindowOptions Object ### Description Position and size settings for the popup window. ### Kind global typedef ### See Please reference the [Window.open()#Window Features](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Window_features) MDN article for more details ### Properties #### top - **top** (String) - Optional #### left - **left** (String) - Optional #### width - **width** (String) - Optional #### height - **height** (String) - Optional ``` -------------------------------- ### Launch Smartcar Connect Dialog in JavaScript Source: https://context7.com/smartcar/javascript-sdk/llms.txt Launches the Smartcar Connect authorization flow in a popup window. It supports custom states, forcing new permissions, pre-selecting vehicle makes, and custom window dimensions. The `onComplete` callback receives the authorization code upon successful user authorization. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info', 'read_odometer', 'control_security'], onComplete: function(error, code, state) { if (error) { document.getElementById('status').textContent = 'Authorization failed: ' + error.message; return; } document.getElementById('status').textContent = 'Vehicle connected!'; sendCodeToBackend(code, state); } }); // Basic popup launch document.getElementById('connect-btn').addEventListener('click', function() { smartcar.openDialog({ state: 'user-' + Date.now() }); }); // Launch with pre-selected make and force new permissions document.getElementById('connect-tesla-btn').addEventListener('click', function() { smartcar.openDialog({ state: 'tesla-flow-' + Date.now(), forcePrompt: true, vehicleInfo: { make: 'TESLA' }, singleSelect: true }); }); // Launch with custom window size and position document.getElementById('connect-custom-btn').addEventListener('click', function() { smartcar.openDialog({ state: 'custom-window', windowOptions: { top: '100', left: '200', width: '500', height: '700' } }); }); ``` -------------------------------- ### JavaScript: Semantic Release Verify Configuration Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This JavaScript file contains the semantic-release configuration for verification. It is run on every CI build to ensure that the local release preparation steps have been correctly executed. ```javascript sr-configs/verify.js // run on every CI build, verifies that local.js has been run ``` -------------------------------- ### Include Smartcar Redirect Helper Script Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Embeds the Smartcar JavaScript SDK's redirect helper script in your backend page. This script is crucial for invoking the `onComplete` callback with authorization parameters and closing the Connect pop-up dialog after a server-side redirect. ```html ``` -------------------------------- ### Include Smartcar JS SDK via CDN Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Includes the Smartcar JavaScript SDK in your HTML file using a Content Delivery Network (CDN). This method is suitable for projects that do not use a module bundler like npm. ```html ``` -------------------------------- ### Shell Script: Release Verification Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This shell script performs the actual verification of release files. It checks package.json, package-lock.json, README.md for correct versioning, and ensures generated JSDoc remains consistent. ```bash verify-release.sh // does the actual verification of the files ``` -------------------------------- ### Generate Smartcar Connect URL with getAuthUrl() Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Generates the Smartcar Connect URL directly without using click handlers or opening dialogs. This method is useful when you need to construct the authorization URL programmatically. It takes an optional `options` object for customization. ```javascript const url = smartcar.getAuthUrl(); ``` -------------------------------- ### JavaScript: Semantic Release Publish Configuration Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This JavaScript file defines the semantic-release configuration for publishing. It is executed on CI for master builds and handles publishing to npm, the CDN, and GitHub releases. ```javascript sr-configs/publish.js // run on CI, but only on master builds, publishes to npm, cdn, & GitHub ``` -------------------------------- ### Add Smartcar Connect Click Handler Source: https://github.com/smartcar/javascript-sdk/blob/master/README.md Attaches a click event listener to an HTML element, specified by its ID, to launch the Smartcar Connect flow when the element is clicked. This provides a user-friendly way to initiate the vehicle connection process. ```javascript smartcar.addClickHandler({id: '#your-button-id'}); ``` -------------------------------- ### JavaScript: Semantic Release Local Configuration Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This JavaScript file contains the local semantic-release configuration. It is intended for use during development and is not run on CI. It helps in preparing the release by updating package versions and templating the README. ```javascript sr-configs/local.js // NOT run on CI, used during development ``` -------------------------------- ### Smartcar Errors Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Details about custom error types thrown by the Smartcar SDK. ```APIDOC ## Smartcar Error Types ### Description The Smartcar SDK provides specific error types to handle different authorization and compatibility issues. ### Error Types - **Smartcar.AccessDenied** - **Description**: Thrown when the user denies access to their vehicle data. - **Constructor**: `new Smartcar.AccessDenied(message)` - **Smartcar.VehicleIncompatible** - **Description**: Thrown when the vehicle is not compatible with Smartcar or the requested scopes. - **Constructor**: `new Smartcar.VehicleIncompatible(message, vehicleInfo)` - **vehicleInfo** (Object) - Information about the incompatible vehicle. - **Smartcar.InvalidSubscription** - **Description**: Thrown when the application's subscription is invalid or expired. - **Constructor**: `new Smartcar.InvalidSubscription(message)` ``` -------------------------------- ### OnComplete Callback Function Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md A global typedef function that is called upon completion of the Smartcar Connect authorization flow. ```APIDOC ## OnComplete Callback Function ### Kind global typedef ### Parameters #### error - **error** (Error) - Optional - something went wrong in Connect; this normally indicates that the user denied access to your application or does not have a connected vehicle #### code - **code** (String) - Required - the authorization code to be exchanged from a backend server for an access token #### state - **state** (Object) - Optional - contains state if it was set on the initial authorization request #### virtualKeyUrl - **virtualKeyUrl** (String) - Optional - virtual key URL used by Tesla to register Smartcar's virtual key on a vehicle. This registration will be required in order to use any commands on a Tesla vehicle. It is an optional argument as it is only included in specific cases. ``` -------------------------------- ### JavaScript: UMD Wrapper for SDK Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This JavaScript file is used by the gulpfile.js to write a UMD (Universal Module Definition) wrapper around the sdk.js file. This ensures the SDK can be used in various module environments. ```javascript returnExports.js // used by gulpfile.js to write a UMD wrapper ``` -------------------------------- ### Generate Smartcar Authorization URL Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Generates the OAuth URL for Smartcar Connect. Allows customization with state, force prompt, vehicle make, single select options, flags, and user identifier. ```javascript const authUrl = smartcar.getAuthUrl({ state: 'YOUR_STATE', forcePrompt: true, vehicleInfo: { make: 'TESLA' }, singleSelect: { vin: 'YOUR_VEHICLE_VIN' }, flags: ['country:DE', 'color:00819D'], user: 'USER_ID' }); console.log(authUrl); ``` -------------------------------- ### Add Click Handler for Authorization Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Attaches a click event listener to an element, which will trigger the opening of the Smartcar Connect dialog when clicked. This is useful for integrating the authorization flow with UI elements. ```javascript const connectButton = document.getElementById('connect-button'); smartcar.addClickHandler(connectButton, { // Options for the dialog }); ``` -------------------------------- ### JavaScript: Write Package Version Source: https://github.com/smartcar/javascript-sdk/blob/master/build/README.md This JavaScript file takes a version number as input and writes it into the package.json and package-lock.json files. It's a crucial step in updating project versions during the release process. ```javascript write-package-version.js // given a version number, writes into package.json and package-lock.json ``` -------------------------------- ### Smartcar.unmount Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Removes the Smartcar Connect dialog from the DOM. ```APIDOC ## smartcar.unmount() ### Description Removes the Smartcar Connect dialog and cleans up associated resources. ### Method `smartcar.unmount()` ### Request Example ```javascript smartcar.unmount(); ``` ``` -------------------------------- ### Handle Smartcar SDK Errors in JavaScript Source: https://context7.com/smartcar/javascript-sdk/llms.txt Demonstrates how to handle various error types returned by the Smartcar SDK during the Connect flow. It checks for specific error names like 'AccessDenied', 'VehicleIncompatible', and 'InvalidSubscription' to provide user-friendly messages and logs. This code requires the Smartcar SDK to be initialized. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info', 'control_security'], onComplete: function(error, code, state, virtualKeyUrl) { if (!error) { // Success - user authorized the application handleSuccess(code, state, virtualKeyUrl); return; } // Handle Smartcar.AccessDenied - user clicked "Deny" or cancelled if (error.name === 'AccessDenied') { showMessage('You denied access to your vehicle. Please try again if this was a mistake.'); logAnalytics('connect_denied', { state }); return; } // Handle Smartcar.VehicleIncompatible - vehicle doesn't support required features if (error.name === 'VehicleIncompatible') { console.log('Vehicle incompatible:', error.message); // vehicleInfo is available if user granted permission to share it if (error.vehicleInfo) { console.log('VIN:', error.vehicleInfo.vin); // string console.log('Make:', error.vehicleInfo.make); // string, e.g., 'TESLA' console.log('Year:', error.vehicleInfo.year); // number, e.g., 2017 console.log('Model:', error.vehicleInfo.model); // string (optional), e.g., 'Model S' showMessage(`Your ${error.vehicleInfo.year} ${error.vehicleInfo.make} is not compatible.`); } else { showMessage('Your vehicle is not compatible with this application.'); } return; } // Handle Smartcar.InvalidSubscription - app subscription issue if (error.name === 'InvalidSubscription') { console.error('Subscription error:', error.message); showMessage('There was a problem with the service. Please contact support.'); return; } // Handle unexpected errors console.error('Unexpected Connect error:', error); showMessage('An unexpected error occurred. Please try again.'); } }); ``` -------------------------------- ### Add Click Handler Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Adds an on-click event listener to a specified DOM element. When the element is clicked, it triggers the Smartcar Connect dialog. ```APIDOC ## POST /smartcar/addClickHandler ### Description Adds an on-click event listener to an element, triggering Smartcar Connect when clicked. ### Method POST ### Endpoint /smartcar/addClickHandler ### Parameters #### Request Body - **id** (String) - Optional - The ID of the element to attach the click handler to. - **selector** (String) - Optional - A CSS selector for the element(s) to attach the click handler to. If `id` is also provided, `id` takes precedence. - **state** (String) - Optional - Arbitrary state passed to the redirect URI. - **forcePrompt** (Boolean) - Optional - Force the permission approval screen to show on every authentication, even if the user has previously consented to the exact scope of permission. Defaults to `false`. - **vehicleInfo.make** (String) - Optional - Allows users to bypass the car brand selection screen. See [API Reference](https://smartcar.com/docs/api#authorization) for supported makes. - **singleSelect** (Boolean | Object) - Optional - Sets the behavior of the grant dialog. If `true`, limits the user to selecting only one vehicle. If an object with a `vin` property, authorizes only the specified vehicle. See [API reference](https://smartcar.com/docs/api/#connect-match) for more information. - **flags** (Array) - Optional - A list of feature flags for early access. - **windowOptions** (WindowOptions) - Optional - Position and size settings for the popup window. ### Request Example ```json { "id": "connect-button", "state": "user-session-123", "forcePrompt": false, "singleSelect": true } ``` ### Response #### Success Response (200) This endpoint does not return a direct response body. It modifies the DOM by adding an event listener. ``` -------------------------------- ### Add Click Handlers for Smartcar Connect in JavaScript Source: https://context7.com/smartcar/javascript-sdk/llms.txt Attaches click event listeners to DOM elements to launch the Smartcar Connect popup. It supports targeting elements by ID or CSS selector, allowing for easy integration of vehicle connection functionality across multiple buttons. Options like `forcePrompt` and `singleSelect` can be configured. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info', 'read_odometer'], onComplete: function(error, code, state) { if (error) return console.error(error); console.log('Received code:', code, 'for flow:', state); } }); // Attach handler by element ID smartcar.addClickHandler({ id: 'connect-car-button', state: 'main-cta-flow', forcePrompt: false }); // Attach handler to multiple elements via CSS selector smartcar.addClickHandler({ selector: '.connect-vehicle-btn', state: 'secondary-cta-flow', singleSelect: true }); // Attach with both ID and selector (handles all matching elements) smartcar.addClickHandler({ id: 'primary-connect', selector: '.nav-connect-btn, .footer-connect-btn', state: 'multi-element-flow', forcePrompt: true, vehicleInfo: { make: 'BMW' } }); // HTML structure example: // // // // ``` -------------------------------- ### Smartcar.getAuthUrl Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Generates the Smartcar OAuth authorization URL, which is used to redirect the user to Smartcar Connect for vehicle authorization. ```APIDOC ## smartcar.getAuthUrl(options) ⇒ String ### Description Generates the Smartcar OAuth URL to initiate the authorization flow. ### Method `smartcar.getAuthUrl(options)` ### Parameters #### Query Parameters - **options** (Object) - Required - Configuration object for the authorization URL. - **state** (String) - Optional - Arbitrary state value to be passed to the redirect URI. - **forcePrompt** (Boolean) - Optional - If true, forces the permission approval screen to show on every authentication, even if the user has previously consented to the exact scope. - **vehicleInfo.make** (String) - Optional - Specifies the vehicle's make to bypass the car brand selection screen. Refer to Smartcar documentation for supported brands. - **singleSelect** (Boolean | Object) - Optional - Controls the behavior of the grant dialog. If `true`, limits the user to selecting one vehicle. If an object with a `vin` property is provided, Smartcar authorizes only that specific VIN. - **flags** (Array) - Optional - A list of feature flags for early access to specific features. - **user** (String) - Optional - A unique identifier for the vehicle owner to aggregate analytics across Connect sessions. ### Response #### Success Response (String) - Returns the generated OAuth URL as a String. ### Request Example ```javascript const authUrl = smartcar.getAuthUrl({ state: '0facda3319', forcePrompt: false, vehicleInfo: { make: 'TESLA' }, singleSelect: true, flags: ['country:DE', 'color:00819D'], user: '2dad4eaf-9094-4bff-bb0f-ffbbdde8b562' }); // authUrl will contain the full OAuth URL ``` ### Response Example ``` https://connect.smartcar.com/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&scope=read_odometer%20read_vehicle_info&redirect_uri=YOUR_REDIRECT_URI&state=0facda3319&make=TESLA&single_select=true&single_select_vin=YOUR_VIN&flags=country:DE%20color:00819D&user=2dad4eaf-9094-4bff-bb0f-ffbbdde8b562 ``` ``` -------------------------------- ### Generate Smartcar Auth URL Source: https://context7.com/smartcar/javascript-sdk/llms.txt Generates the Smartcar Connect OAuth URL with configured parameters. This method is useful for custom implementations or server-side redirects when not using the popup dialog. It supports options for state, force prompt, pre-selecting vehicle makes, single vehicle selection, specific VIN authorization, feature flags, and user tracking. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info', 'read_odometer'], onComplete: function(error, code) {} }); // Basic URL generation const basicUrl = smartcar.getAuthUrl(); // Output: https://connect.smartcar.com/oauth/authorize?response_type=code&client_id=8229df9f-91a0-4ff0-a1ae-a1f38ee24d07&redirect_uri=...&approval_prompt=auto&scope=read_vehicle_info%20read_odometer&mode=live&state=... // URL with state for CSRF protection and user tracking const urlWithState = smartcar.getAuthUrl({ state: 'user-session-token-abc123', forcePrompt: true // Force permission screen even if previously authorized }); // URL pre-selecting vehicle make (skip brand selection) const teslaOnlyUrl = smartcar.getAuthUrl({ state: 'session-xyz', vehicleInfo: { make: 'TESLA' } }); // URL for single vehicle selection const singleSelectUrl = smartcar.getAuthUrl({ state: 'session-xyz', singleSelect: true // User can only select one vehicle }); // URL for specific VIN authorization (Connect Match) const specificVinUrl = smartcar.getAuthUrl({ state: 'session-xyz', singleSelect: { vin: '5YJSA1E14FF101307' } }); // URL with feature flags and user tracking const advancedUrl = smartcar.getAuthUrl({ state: 'session-xyz', forcePrompt: true, vehicleInfo: { make: 'TESLA' }, singleSelect: true, flags: ['country:DE', 'color:00819D'], user: '2dad4eaf-9094-4bff-bb0f-ffbbdde8b562' // Analytics user ID }); ``` -------------------------------- ### Smartcar.InvalidSubscription Error Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Represents an error when an invalid subscription is encountered with the Smartcar Connect service. ```APIDOC ## Smartcar.InvalidSubscription Error ### Description Invalid subscription error returned by Connect. ### Kind static class of [Smartcar](#Smartcar) ### Extends Error ### Constructor #### new Smartcar.InvalidSubscription(message) ### Parameters #### message - **message** (String) - Required - detailed error description ``` -------------------------------- ### Unmount Smartcar SDK Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Removes all event listeners added by the Smartcar SDK, including the global message listener for authorization codes and any click event listeners attached to DOM elements. ```APIDOC ## DELETE /smartcar/unmount ### Description Removes Smartcar's event listeners, including the global message listener and any attached click handlers. ### Method DELETE ### Endpoint /smartcar/unmount ### Parameters This endpoint does not accept any parameters. ### Request Example ```json {} // Empty request body ``` ### Response #### Success Response (200) This endpoint does not return a direct response body. It performs cleanup operations by removing event listeners. ``` -------------------------------- ### Unmount Smartcar SDK Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Removes any event listeners and cleans up resources associated with the Smartcar SDK instance. This should be called when the SDK is no longer needed to prevent memory leaks. ```javascript smartcar.unmount(); ``` -------------------------------- ### Smartcar.VehicleIncompatible Error Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Represents an error when a vehicle is incompatible with the Smartcar Connect service. It may optionally include vehicle information if the user grants permission. ```APIDOC ## Smartcar.VehicleIncompatible Error ### Description Vehicle incompatible error returned by Connect. Will optionally have a vehicleInfo object if the user chooses to give permissions to provide that information. See our [Connect documentation](https://smartcar.com/docs/api#smartcar-connect) for more details. ### Kind static class of [Smartcar](#Smartcar) ### Extends Error ### Constructor #### new Smartcar.VehicleIncompatible(message, vehicleInfo) ### Parameters #### message - **message** (String) - Required - detailed error description #### vehicleInfo - **vehicleInfo** (Object) - Optional - If a vehicle is incompatible, the user has the option to return vehicleInfo to the application. - **vehicleInfo.vin** (String) - Optional - returned if user gives permission. - **vehicleInfo.make** (String) - Optional - returned if user gives permission. - **vehicleInfo.year** (Number) - Optional - returned if user gives permission. - **vehicleInfo.model** (String) - Optional - optionally returned if user gives permission. ``` -------------------------------- ### Smartcar Error Types Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Defines custom error classes for specific Smartcar authorization failures. These include AccessDenied, VehicleIncompatible, and InvalidSubscription, providing specific details about the error. ```javascript // Example of catching an error try { // ... Smartcar operations ... } catch (error) { if (error instanceof Smartcar.AccessDenied) { console.error('Access Denied:', error.message); } else if (error instanceof Smartcar.VehicleIncompatible) { console.error('Vehicle Incompatible:', error.message, error.vehicleInfo); } else if (error instanceof Smartcar.InvalidSubscription) { console.error('Invalid Subscription:', error.message); } else { console.error('An unexpected error occurred:', error); } } ``` -------------------------------- ### Smartcar Error Types Source: https://github.com/smartcar/javascript-sdk/blob/master/doc/README.md Defines custom error types thrown by the Smartcar SDK, such as AccessDenied. ```APIDOC ## Smartcar Error Classes ### Description Provides information about custom error classes used within the Smartcar SDK. ### Classes #### `Smartcar.AccessDenied` **Kind**: static class of `Smartcar` **Extends**: `Error` ##### Constructor `new Smartcar.AccessDenied(message: String)` - **message** (String) - A detailed description of the access denied error. ``` -------------------------------- ### Unmount Smartcar Event Listeners in JavaScript Source: https://context7.com/smartcar/javascript-sdk/llms.txt Removes all Smartcar event listeners from the window and associated DOM elements. This is crucial for preventing memory leaks and stale event handlers, especially when the component using the SDK is unmounted or destroyed. It should be called during the cleanup phase of component lifecycles. ```javascript const smartcar = new Smartcar({ clientId: '8229df9f-91a0-4ff0-a1ae-a1f38ee24d07', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info'], onComplete: function(error, code) { if (error) return console.error(error); console.log('Code received:', code); } }); // Set up click handlers smartcar.addClickHandler({ id: 'connect-btn', state: 'flow-1' }); smartcar.addClickHandler({ selector: '.vehicle-connect', state: 'flow-2' }); // Later, when component unmounts or user navigates away function cleanup() { smartcar.unmount(); console.log('Smartcar listeners removed'); } // React example with hooks function VehicleConnect() { useEffect(() => { const smartcar = new Smartcar({ clientId: 'your-client-id', redirectUri: 'https://javascript-sdk.smartcar.com/v2/redirect?app_origin=https://myapp.com', scope: ['read_vehicle_info'], onComplete: (error, code) => { if (!error) sendToBackend(code); } }); smartcar.addClickHandler({ id: 'connect-btn' }); // Cleanup on unmount return () => smartcar.unmount(); }, []); return ; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.