puffinOffsetCalculator/puffin-calculator.js

94 lines
3.4 KiB
JavaScript

/**
* Puffin Offset Calculator WordPress Plugin Script
* This script handles communication between WordPress and the calculator iframe
*/
(function($) {
'use strict';
// Wait for the DOM to be fully loaded
$(document).ready(function() {
// Get all calculator iframes
const calculatorIframes = $('.puffin-calculator-iframe');
if (calculatorIframes.length === 0) {
return;
}
// Process each iframe
calculatorIframes.each(function() {
const iframe = $(this);
// Set up message listener for iframe communication
window.addEventListener('message', function(event) {
// Make sure the message is from our calculator
if (!event.origin.includes('localhost:8080') &&
!event.origin.includes('puffinoffset.com')) {
return;
}
// Handle different message types
if (event.data && typeof event.data === 'object') {
switch (event.data.type) {
case 'resize':
// Resize iframe based on content height
if (event.data.height) {
iframe.height(event.data.height);
}
break;
case 'calculationComplete':
// Handle when a calculation is completed
console.log('Calculation completed:', event.data.result);
// You could trigger WordPress events or update page content here
break;
case 'offsetPurchased':
// Handle when a user purchases an offset
console.log('Offset purchased:', event.data.details);
// You could trigger analytics events or show WordPress notifications
break;
}
}
});
// Send init message to iframe once loaded
iframe.on('load', function() {
const message = {
type: 'init',
source: 'wordpress',
siteInfo: {
name: document.title,
url: window.location.href
}
};
// Post message to iframe
try {
iframe[0].contentWindow.postMessage(message, '*');
} catch (e) {
console.error('Failed to initialize calculator communication:', e);
}
});
});
// Adjust iframe height on window resize
$(window).on('resize', function() {
calculatorIframes.each(function() {
const iframe = $(this);
const message = {
type: 'requestHeight',
source: 'wordpress'
};
try {
iframe[0].contentWindow.postMessage(message, '*');
} catch (e) {
// Iframe might not be loaded yet
}
});
});
});
})(jQuery);