How to execute js code on Google Optimize?

380 Views Asked by At

Using Google Optimize, I've added a button in a website that on the click needs to activate a js code that makes an API call.

Testing the code outside the Optimize it is running well, but using it in Optimize, when I click on the button, the console returns a message saying "Uncaught ReferenceError:loadXMLDoc is not defined".

Here is the HTML added

<button type="button" onclick="loadXMLDoc()">Call API</button>

Here is the JavaScript code added

function loadXMLDoc() {
    let url = "https://api.api4com.com/api/v1/calls?access_token="
    //const fone = console.log(document.getElementsByClassName("maks-phone-deal")[1].value);
    const fone = document.getElementsByClassName("maks-phone-deal")[1].value
    const deal_id = document.getElementsByClassName("deal-details")[0].attributes[1].value
    const instancia = document.URL.split(".")[0].replace("https://","")
   
    const body = {
      caller: "1001",
      //called: ${fone},
      called: fone,
      extension: "1001",
      metadata: {
        api4comAccessToken: "",
        gateway: "facilita",
        instancia: instancia,
        negocio: deal_id
      }}

   

fazPost(url, body)

}

function fazPost(url, body){
    console.log("Body=",body)
    let request = new XMLHttpRequest()
    request.open("POST", url, true)
    request.setRequestHeader("Content-type", "application/json")
    request.send(JSON.stringify(body))

    request.onload = function(){
        console.log(this.responseText)
    }

    return request.responseText
}

image1

image2

image3

The result was that the function loadXMLDoc is not defined.

It is the message returned in the console: "Uncaught ReferenceError:loadXMLDoc is not defined"

1

There are 1 best solutions below

1
Thiago Guimarães On

Try add JavaScript to element

Into Element Selector set your target, than in your case is a button After enter a Javascript junction, like this:

function loadXMLDoc() {/**your code*/}
document.querySelector('body>button').onclick = loadXML