woocommerce-paypal-payments/modules/ppcp-googlepay/resources/js/Block/hooks/useGooglepayScript.js

66 lines
1.5 KiB
JavaScript
Raw Normal View History

2024-10-09 16:38:11 +02:00
import { useState, useEffect } from '@wordpress/element';
import { loadCustomScript } from '@paypal/paypal-js';
const useGooglepayScript = (
componentDocument,
buttonConfig,
isPayPalLoaded
) => {
2024-10-09 16:38:11 +02:00
const [ isGooglepayLoaded, setIsGooglepayLoaded ] = useState( false );
useEffect( () => {
if ( ! componentDocument ) {
return;
}
const injectScriptToFrame = ( scriptSrc ) => {
if ( document === componentDocument ) {
return;
}
const script = document.querySelector(
`script[src^="${ scriptSrc }"]`
);
if ( script ) {
const newScript = componentDocument.createElement( 'script' );
newScript.src = script.src;
newScript.async = script.async;
newScript.type = script.type;
componentDocument.head.appendChild( newScript );
} else {
console.error( 'Script not found in the document:', scriptSrc );
}
};
2024-10-09 16:38:11 +02:00
const loadGooglepayScript = async () => {
if ( ! isPayPalLoaded ) {
return;
}
if ( ! buttonConfig || ! buttonConfig.sdk_url ) {
console.error( 'Invalid buttonConfig or missing sdk_url' );
return;
}
try {
await loadCustomScript( { url: buttonConfig.sdk_url } ).then(
() => {
injectScriptToFrame( buttonConfig.sdk_url );
}
);
2024-10-09 16:38:11 +02:00
setIsGooglepayLoaded( true );
} catch ( error ) {
console.error( 'Failed to load Googlepay script:', error );
}
};
loadGooglepayScript();
}, [ componentDocument, buttonConfig, isPayPalLoaded ] );
2024-10-09 16:38:11 +02:00
return isGooglepayLoaded;
};
export default useGooglepayScript;