Vanilla JS
This guide provides a comprehensive, step-by-step process to create your first custom widget using Vanilla JavaScript and the TakeProfit Widget SDK (version 0.2.3). By following this guide, you’ll set up a simple project structure, integrate the SDK, configure necessary security headers, and implement basic functionalities to interact with the TakeProfit platform. This example serves as a foundation for building more complex and feature-rich widgets tailored to your specific needs.
Prerequisites
Before you begin, ensure you have the following:
- Node.js: Version 14 or higher. Download from Node.js Official Website.
- npm or Yarn: Package managers that come with Node.js.
- Code Editor: Such as Visual Studio Code.
- Basic Knowledge: Familiarity with JavaScript, HTML, and CSS.
- Access to TakeProfit Platform: For widget integration and testing.
Set Up Your Project Structure
-
Create a Project Directory
Open your terminal and create a new directory for your widget:
-
Initialize npm
Initialize a new npm project to manage dependencies:
-
Create Essential Files and Folders
Set up the basic structure:
Your project structure should look like this:
Include the TakeProfit Widget SDK
-
Download the SDK
Since you’re using Vanilla JavaScript, it’s easiest to include the SDK via a CDN. Ensure you reference version 0.2.3.
-
Add the SDK Script to
index.html
Open
src/index.html
and include the SDK script:Explanation:
- The SDK is included via a CDN link pointing to version 0.2.3.
- Basic HTML structure with buttons to interact with the SDK.
Configure Security Headers
To ensure that your widget can be embedded securely within the TakeProfit platform, you need to configure specific HTTP headers. Since you’re using Vanilla JavaScript without a build tool, you’ll need to set up a simple server to serve your widget with the necessary headers.
-
Install
http-server
Use
http-server
to serve your files with custom headers. -
Create a
server.js
FileCreate a simple Node.js server to serve your widget with the required headers.
Open
server.js
and add the following code:Explanation:
- The server serves files from the
src
directory. - Sets
X-Frame-Options
andContent-Security-Policy
headers to allow embedding only fromhttps://takeprofit.com
. - Handles 404 errors with a custom
404.html
page (create this file if desired).
- The server serves files from the
-
Create a
404.html
Page (Optional) -
Start the Server
Run the server to serve your widget with the configured headers:
Your widget will be accessible at
http://localhost:8080
.
Initialize the SDK
-
Modify
app.js
to Initialize the SDKOpen
src/app.js
and add the following code:Explanation:
initializeSDK
: Connects to the TakeProfit platform and hides the loader. Subscribes to widget and channel state changes.cleanupSDK
: Disconnects from the SDK when the widget is unloaded.
Create the Widget UI
-
Update
index.html
with Interactive ElementsEnsure your
index.html
includes buttons to interact with the SDK: -
Style the Widget with
styles.css
Add basic styling to
src/styles.css
:Explanation:
- Centers the widget on the page.
- Styles buttons for better user experience.
Manage Widget State and Interactions
-
Update
app.js
to Handle Button ClicksEnhance
src/app.js
to handle interactions:Important Corrections:
- Conditional Checks: Updated
if (result.isSuccessful)
toif (result.payload.isSuccessful)
to correctly access theisSuccessful
property within thepayload
. - Error Messages: Updated
${result.error}
to${result.payload.error}
to correctly access theerror
message within thepayload
.
Explanation:
- Button Event Listeners: Adds event listeners to handle user interactions.
- Security Change: Changes the displayed security to AAPL or META.
- Menu Items: Functions to add, update, and remove a “Refresh Data” menu item. Enables or disables update/remove buttons based on the menu item’s state.
- Conditional Checks: Updated
Add Menu Items
-
Implement Menu Item Functions in
app.js
The menu item functions are already implemented in Step 6. Here’s a recap:
-
Add Menu Item
-
Update Menu Item
-
Remove Menu Item
Explanation:
- Add Menu Item: Adds a new menu item labeled “Refresh Data”. Upon successful addition, enables the update and remove buttons.
- Update Menu Item: Updates the existing menu item’s label.
- Remove Menu Item: Removes the menu item and disables the update and remove buttons.
-
Test Your Widget Locally
-
Start the Server
Ensure your server is running to serve the widget with the configured headers:
Your widget will be accessible at
http://localhost:8080
. -
Configure Local Storage for Testing
To simulate the widget’s presence on the TakeProfit platform, configure local storage in your browser:
-
Open the TakeProfit Platform: Navigate to the TakeProfit platform in your browser.
-
Open Developer Console: Press
F12
orCtrl+Shift+I
to open the developer tools. -
Set Local Storage Entry:
Note:
- Replace
'http://localhost:8080'
with your actual widget URL if different. - Provide a valid
imageUrl
for the widget icon.
- Replace
-
-
Reload the TakeProfit Platform
Refresh the TakeProfit platform page. Your Vanilla JavaScript widget should now appear in the widget panel, allowing you to add it to the dashboard and interact with its functionalities.
-
Verify Functionality
- Security Change: Click on the “Set Security” buttons and observe the console logs for successful changes.
- Menu Items: Add the “Refresh Data” menu item and click it to see the corresponding console log. Test updating and removing the menu item to ensure they function as expected.
Deploy Your Widget
Once testing is successful, deploy your widget to a live environment.
-
Choose a Hosting Service
Select a hosting service that can serve static files and supports custom HTTP headers. Some popular options include:
- Netlify
- Vercel
- GitHub Pages
- AWS S3 with CloudFront
-
Prepare Your Files for Deployment
Ensure all your files (
index.html
,styles.css
,app.js
, etc.) are correctly set up and that your server configuration (server.js
) is compatible with your hosting service. Some hosting services like Netlify and Vercel handle headers via configuration files. -
Deploy to Netlify (Example)
Here’s how to deploy your widget to Netlify with the necessary headers:
-
Create a
netlify.toml
File -
Deploy via Netlify CLI or Git Integration
-
Using Git Integration:
- Push your project to a Git repository (GitHub, GitLab, etc.).
- Connect your repository to Netlify through the Netlify dashboard.
- Netlify will automatically build and deploy your site based on the
netlify.toml
configuration.
-
Using Netlify CLI:
-
Install Netlify CLI:
-
Deploy:
-
-
-
-
Update Local Storage Configuration
After deployment, update the
iframeUrl
in the TakeProfit platform’s local storage to point to your deployed widget’s URL: -
Final Testing
Reload the TakeProfit platform and verify that your deployed widget functions correctly in the live environment. Test all functionalities, including security changes and menu item interactions, to ensure seamless integration.
Best Practices
-
Secure Communication: Always serve your widget over HTTPS to ensure secure communication with the TakeProfit platform.
-
Unique Identifiers: Ensure that
requestId
andmenuItemId
are unique to prevent conflicts. -
Subscription Management: Always unsubscribe from state changes when they’re no longer needed to prevent memory leaks.
-
Error Handling: Implement robust error handling for all asynchronous operations to enhance user experience.
-
Performance Optimization: Limit the number of active subscriptions and avoid unnecessary state updates to maintain optimal performance.
-
Code Documentation: Keep your code well-documented to facilitate maintenance and future enhancements.
-
Responsive Design: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
Next Steps
Congratulations! You’ve successfully created and integrated your first widget using Vanilla JavaScript and the TakeProfit Widget SDK (version 0.2.3). To further enhance your widget, consider the following:
- Explore Advanced SDK Features: Refer to the SDK Reference to utilize all available methods and message types.
- Implement Real-Time Data: Integrate real-time data feeds to provide dynamic and up-to-date information within your widget.
- Customize the UI: Enhance the user interface with additional HTML elements and CSS styling to improve user engagement.
- Add More Interactions: Implement more interactive features like custom events, notifications, and user preferences.
- Optimize: Ensure your widget is responsive and functions seamlessly across different devices and screen sizes.
- Security Enhancements: Implement additional security measures to safeguard data and ensure secure communication.
For comprehensive details, refer to the SDK Reference and other documentation resources provided by the TakeProfit Widget SDK.
Troubleshooting
If you encounter issues while setting up or using the TakeProfit Widget SDK, consider the following solutions:
-
SDK Not Connecting
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
takeprofit.com
). - Network Issues: Verify that there are no network restrictions or firewall rules blocking communication.
- Check Origins: Ensure that your widget’s domain is allowed and matches the trusted origins (
-
Menu Items Not Appearing
- Local Storage Configuration: Double-check the
iframeUrl
and ensure it points to the correct widget URL. - SDK Initialization: Ensure that
TPWidgetSDK.connect()
andTPWidgetSDK.hideLoader()
are called successfully.
- Local Storage Configuration: Double-check the
-
Security Change Fails
- Valid Security ID: Ensure that the
securityID
you are requesting is valid and recognized by the platform. - Error Handling: Check the console for error messages to understand why the request failed.
- Valid Security ID: Ensure that the
-
Unhandled Promise Rejections
- Implement
.catch
Blocks: Ensure that all asynchronous SDK methods have proper error handling using.catch
to manage rejected promises.
- Implement
-
Performance Issues
- Optimize Subscriptions: Limit the number of active subscriptions and avoid unnecessary state updates.
- Efficient Rendering: Ensure that your JavaScript code is optimized to prevent unnecessary operations.
For persistent issues, refer to the Support and Resources section or contact the support team for assistance.
Additional Resources
- Installation Guide: Detailed instructions for installing the SDK.
- SDK Reference: Comprehensive documentation of all available methods, interfaces, and message types.
- Creating Your First Widget: A practical guide to building and testing a basic widget.
- JavaScript Documentation: Official JavaScript documentation for deeper understanding.
- Content Security Policy (CSP) Documentation: Learn more about CSP for enhancing security.
- HTTP Headers Documentation: Understand various HTTP headers for better configuration.