简体   繁体   中英

How to Replace Text Within Script Tags Using JQuery

We use a page builder (ClickFunnels) to build pages. On these pages are different scripts, eg Facebook pixel.

We are cloning these pages a lot and run various tests. Currently, we update the scripts manually, but we would like to semi-automate it.

During build time (in the editor) we want to make changes to these scripts (change strings) using the browser console. We then just paste a script into the console and that will do all changes for us. We then save the page and the scripts are updated.

To be clear this is not during runtime but during build time of the pages. The scripts to be changed haven't been and won't be executed in the editor.

Here's an example of one script (stripped down, because how the script works is not important here):

<script id="facebookPixel">

!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
document,'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('set', 'autoConfig', false, '123123123');

fbq('track', 'Purchase', {

content_ids: [456465456] //this is a random number
 });

</script>

Now the question: How can I access the content of script tags with jQuery?

I tried .text, .html, .innerHTML, but they don't return the actual content.

What I ultimately like to do is replacing the string "content_ids: [randomnumber]" with "content_ids: [myNewNumber]"

I also tried this advice without success: https://stackoverflow.com/a/31598972/5072891

You could use regular expression, remove the script tag and append a newly created one:

 let scriptStr = $("#facebookPixel").html().replace(/content_ids: \\[+(.*?)\\]/, 'contents_id: [345, 567]'); $("#facebookPixel").remove(); let script = document.createElement('script'); script.id = "facebookPixel"; script.innerHTML = scriptStr; $(document.head).append(script); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script id="facebookPixel"> !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('set', 'autoConfig', false, '123123123'); fbq('track', 'Purchase', { content_ids: [456465456] //this is a random number }); </script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM