1

The intention is to add an analytics API script to the AMP version of a set of pages in the website.

To do so, I am trying to write a custom AMP script in which I am receiving a dynamic $post_id value from php to a javascript function.

// api_call_component.php

    <amp-script script="page_view">
        <div style="height: 5px"></div>
    </amp-script>
    <script id="page_view" type="text/plain" target="amp-script">
        function page_view(type, id) {
            let formData = `page_type=${type}&id=${id}`
            fetch("my_url/api/add_page_view", {
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, 
                body: formData
            })
        }
        page_view('post', <?php echo $post_id ?>) // this line changes with every post_id
    </script>

The function implementation seeems to work fine except that AMP asks for a new script hash every time the value I need to pass changes.

So I think I need to implement a non dynamic script somehow?

I tried workarounds: getting post_id from URL instead of passing it from the php app. This failed because AMP pages create a new AMP url. I also tried using some of these WorkerDOM methods to get a post_id but got undefined values.

Document.URL, URL.href  // undefined

An alternative would be trying to find the post_id in the dom elements

But maybe there is a more simple / correct solution?

MrFacundo
  • 167
  • 3
  • 13

0 Answers0