Wix:嵌入HTML代码与Velo后端代码能否实现通信?
Great question! The short answer is yes, you can communicate between your HTML embed and Velo backend scripts—they aren’t fully isolated, but since the HTML embed runs in an iframe, you’ll need to use the postMessage API to bridge the gap between the embed and the parent Wix page, which can then call your backend function.
Here’s a step-by-step breakdown of how to set this up:
1. Your Backend Script (Keep as is)
First, your existing backend code looks solid—no changes needed here. It handles fetching data from your collection correctly:
import { sql } from '@velo/wix-data-sql-backend'; export async function fetchData() { try { const results = await sql("SELECT * FROM collection;"); return results.payload.data.rows; } catch (error) { console.error(error); throw error; // Re-throw so the page code can handle the error gracefully } }
2. Wix Page Code (Bridge Between Embed and Backend)
On the Wix page where your HTML embed is placed, add this code to listen for messages from the embed, call the backend function, and send the result back:
import { fetchData } from 'backend/dataModule'; // Adjust the path to match your backend file name $w.onReady(function () { // Listen for incoming messages from the HTML embed window.addEventListener('message', async (event) => { // Critical: Validate the origin to block malicious cross-site messages if (event.origin !== "https://your-wix-site-url.com") return; // Replace with your actual site URL if (event.data.type === 'FETCH_DATA') { try { const data = await fetchData(); // Send successful data back to the embed event.source.postMessage({ type: 'FETCH_DATA_SUCCESS', payload: data }, event.origin); } catch (error) { // Send error details back to the embed event.source.postMessage({ type: 'FETCH_DATA_ERROR', payload: error.message }, event.origin); } } }); });
3. HTML Embed Code (Initiate Request and Receive Response)
In your HTML embed, add code to send a request to the parent Wix page and handle the returned data:
<!DOCTYPE html> <html> <body> <!-- Your drag-and-drop functionality code goes here --> <script> // Function to request backend data via the parent Wix page async function getBackendData() { return new Promise((resolve, reject) => { // Send a message to trigger the backend call window.parent.postMessage({ type: 'FETCH_DATA' }, "https://your-wix-site-url.com"); // Use your site URL // Listen for the response from the parent page const handleResponse = (event) => { if (event.origin !== "https://your-wix-site-url.com") return; // Validate origin again if (event.data.type === 'FETCH_DATA_SUCCESS') { resolve(event.data.payload); window.removeEventListener('message', handleResponse); // Clean up listener } else if (event.data.type === 'FETCH_DATA_ERROR') { reject(new Error(event.data.payload)); window.removeEventListener('message', handleResponse); } }; window.addEventListener('message', handleResponse); }); } // Example usage: Call this when you need to load data for your drag elements getBackendData() .then(data => { console.log("Fetched backend data:", data); // Integrate this data into your draggable elements logic }) .catch(error => { console.error("Failed to fetch data:", error); }); </script> </body> </html>
Key Things to Remember:
- Origin Validation: Never skip checking
event.origin—this prevents malicious third-party sites from sending fake messages to your code. - Message Structure: Using a
typefield in your messages helps organize different request/response types (handy if you add more features later). - Error Handling: Properly catching and propagating errors ensures you can debug issues without silent failures.
This setup lets your HTML embed access backend data while maintaining security. For your drag functionality, just call getBackendData() whenever you need to retrieve or update data for your draggable elements.
内容的提问来源于stack exchange,提问作者Exit Code 1

