If you have a client who has a third party script that has to be placed in the content area of a page, you will find that the content areas of the CMS will strip out any scripts you place in these areas as they are not meant to be loading inline from a content area. To avoid having to create a custom template just to hardcode one of these scripts, you can use the following script which will:
- Be placed in the Header/Footer area of the CMS for the specific page–can go in either one.
- The script will target a placeholder div element that has a particular ID and inject the required script into the page wherever this div element is being placed.
1. Code for Header/Footer area of the Page settings
<script>
function injectCustomScript(target,scriptsource,id) {
let scriptTarget = document.getElementById("targetScript");
if(scriptTarget) {
let script = document.createElement('script');
script.type="text/javascript";
if(id) { script.id=id; } /* If a specific ID is required on the script tag, it can be included as an argument in the function call, opr left blank */
script.src=scriptsource; /* setting the script source to the third party script URL */
scriptTarget.innerHTML = ""; /* removing the placehold text of the content area div */
scriptTarget.appendChild(script);
}
}
window.addEventListener("load", (event) => {
injectCustomScript("targetScript", "CUSTOMSCRIPT_URL","OPTIONALIDVALUE");
});
</script>
NOTE: In the code above, you would only need to set the CUSTOMSCRIPT_URL and an optional script ID, OPTIONALIDVALUE, if it is required to function.
2. In the content area where you want the third party element to show, place this code:
<div id="targetScript">[script placeholder]</div>
Save the content and publish and whatever script you are loading should be injected into the content and run the same as if it were hard coded in a custom template.
Tags: custom scripts, third-party, api