Advanced Widget Usage
While Trycolors widgets provide powerful color mixing and matching capabilities out of the box, they also offer advanced functionality for developers who want to create more dynamic and interactive experiences. This guide explores how to use the postMessage API to communicate between your webpage and the embedded Trycolors widget.
Using postMessage with Trycolors Widgets
Trycolors widgets can send data back to the parent page where they're embedded using the postMessage API. This allows you to capture the results of color operations performed within the widget and use them in your own application logic.
Supported Methods
The following methods are supported for different widget types:
mix-colors
: Available in Mixer and Unmixer widgetsunmix-color
: Available in Unmixer widgetsimilar-paints
: Available in Similar Paints widgetreset-colors
: Available in Mixer and Unmixer widgets
The reset-colors
method is triggered when the user clicks the reset button in any widget. It doesn't carry any payload but notifies the parent page that the widget has been reset to its initial state.
Example Implementation
Here's a complete example of how to implement this functionality:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Widget Parent Page</title>
</head>
<body>
<!-- Embedding the widget using an iframe -->
<iframe
src="https://trycolors.com/widget?token=9dee0dd9-7d24-496d-affd-a85b41e7d765"
width="600"
height="500"
frameborder="0"
allowfullscreen
></iframe>
<!-- Div elements to display the results of mix-colors and unmix-color messages -->
<div>
<h3>Mix Colors Result:</h3>
<pre id="mixColorsResult"></pre>
</div>
<div>
<h3>Unmix Color Result:</h3>
<pre id="unmixColorResult"></pre>
</div>
<div>
<h3>Widget Status:</h3>
<p id="widgetStatus">Active</p>
</div>
<script>
// Example functions that could be called with the received data
function handleMixColors(response) {
console.log("Handling mix colors:", response);
// Add your custom logic here, e.g., update the UI, process data, etc.
}
function handleUnmixColor(response) {
console.log("Handling unmix color:", response);
// Add your custom logic here, e.g., update the UI, process data, etc.
}
function handleReset() {
console.log("Widget has been reset");
document.getElementById("widgetStatus").textContent = "Reset";
// Clear the output of HTML elements under the widget
document.getElementById("mixColorsResult").textContent = "";
document.getElementById("unmixColorResult").textContent = "";
}
// Add an event listener for the 'message' event on the window
window.addEventListener("message", function (event) {
// Ensure the message is from the trusted origin 'trycolors.com'
if (event.origin !== "https://trycolors.com") {
return; // Exit the function if the origin is not trusted
}
// Extract the data from the event
const data = event.data;
// Check the 'method' property of the data to determine the type of message
switch (data.method) {
case "mix-colors":
handleMixColors(data.response);
document.getElementById("mixColorsResult").textContent =
JSON.stringify(data.response, null, 2);
break;
case "unmix-color":
handleUnmixColor(data.response);
document.getElementById("unmixColorResult").textContent =
JSON.stringify(data.response, null, 2);
break;
case "reset-colors":
handleReset();
break;
case "similar-paints":
console.log("Similar paints:", data.response);
// Add logic to handle similar paints data if needed
break;
default:
console.log("Unknown method:", data.method);
}
});
</script>
</body>
</html>
You can view the code and interact with this example in the tabs above.
Advantages of This Approach
Using the postMessage functionality with Trycolors widgets offers several advantages:
-
Seamless UI Integration: You get a fully functional, user-friendly interface for color operations without having to build it yourself.
-
Real-time Data Access: You can capture the results of user interactions with the widget in real-time, allowing for dynamic updates to your page.
-
API-like Functionality: The data you receive is similar to what you'd get from the Trycolors API, but without the need for direct API calls or handling authentication.
-
Reduced Development Time: By leveraging the existing widget UI, you can focus on how to use the color data rather than on creating color mixing interfaces.
-
Dynamic Product Recommendations: Use the color data to dynamically suggest products or content based on user color choices.
-
Enhanced User Experience: Combine the intuitive widget interface with your own custom functionality for a rich, interactive user experience.
-
Flexibility: You can use the same widget in different contexts, processing the data differently based on the specific needs of each page or application.
-
State Synchronization: With the
reset-colors
method, you can keep your application state in sync with the widget's state, allowing for more coherent user experiences.
This approach gives you the best of both worlds: a professional, ready-to-use color interface, and the flexibility to process and use the resulting data in any way that fits your application's needs.
Security Considerations
When implementing this functionality, always ensure you're checking the origin of the received messages to prevent potential security issues:
if (event.origin !== "https://trycolors.com") {
return; // Exit the function if the origin is not trusted
}
This check ensures that your page only processes messages from the trusted Trycolors domain.
Next Steps
- Explore the different widget types to see which best fits your needs
- Learn about widget configuration options to customize your embedded widgets
- Check out our API documentation for more details on the data structures you'll receive
For any questions or support regarding advanced widget usage, please contact our support team (opens in a new tab).