How to send a POST request from GTM custom tag template?

北城以北 提交于 2020-06-01 05:45:26

问题


I'm developing a simple custom tag template for Google Tag Manager. It's supposed to bind to some events and send event data to our servers as JSON in the body of a POST request.

The sandboxed GTM Javascript runtime provides the sendPixel() API. However, that only provides GET requests.

How one sends a POST request from within this sandboxed runtime?


回答1:


You can use a combination of the injectScript and copyFromWindow APIs found here Custom Template APIs.

Basically, the workflow goes like this.

  1. Build a simple script that contains a function attached to the window object that sends a normal XHR post request. The script I made and use can be found here: https://storage.googleapis.com/common-scripts/basicMethods.js
  2. Upload that script somewhere publically accessible so you can import it into your template.
  3. Use the injectScript API to add the script to your custom template.
  4. The injectScript API wants you to provide an onSuccess callback function. Within that function, use the copyWindow api to grab the post request function you created in your script and save it as a variable.
  5. You can now use that variable to send a post request the same way you would use a normal JS function.

The script I included above also includes JSON encode and Base64 encode functions which you can use the same way via the copyWindow api.

I hope that helps. If you need some specific code examples for parts I can help.



来源:https://stackoverflow.com/questions/58825052/how-to-send-a-post-request-from-gtm-custom-tag-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!