Needed Worker & input

Hey guys - I’m not a developer - Digital marketer.

Its my first time working with workers. I have been playing around with it and doing some reading.

I love some help creating a recipe - What I would require = I’m working on client site, would like like that when someone lands on specific page - wwww…operators/contact the worker will trigger a speak script that I wrote.

How would I go about this? I can post the script for context if that helps.

What is that? Workers are basically server-side for the sake of the users, so no speech there for sure…

Sorry - Meant to say specific***

Oh, I see.

That is basically the Worker’s definition. The script runs on the paths (or routes as they call them) you define. If you want the script to run for example every time someone asks for the you would that in the routes and then handle that request from inside the Worker itself.

I usually tend to suggest that people, even if they use a single route at the beginning, write code to handle multiple routes.

@matteo - That seems like it makes sense.
Do you mind if I ask for your input again? I primarily work with the google tag manager and have been using a script (Data Layer). Do you think a script like this would be applicable?

I really need the worker to just push the data so that the tag manager is able to read it on the website.

Have attached the script for more context.

You need to inject that JS file into HTML, since you can’t do it manually on the server?

Yeah that’s correct… any ideas how I would do that

Great question!

I worked up a little example for you, but I’ll give the code snippet here in case it’s useful for other people:

The best way to do this right now IMO is to use text replacement inside of a Workers script to append a script tag into the text of the response, before sending it back to the client.

const script = "<script src=''></script>"

async function handleRequest(request) {
  const response = await fetch(request)
  const body = await response.text()
  const newBody = body.replace("</body>", [script, "</body>"].join(""))
  const newResp = new Response(newBody, response)
  return newResp

In short, this script:

  1. Completes the original request, setting it to the variable response
  2. Gets the text of that response's body, setting it to body
  3. Replaces the end of the body section of your response (</body>), adding a new script tag to the end of it, and sets it to newBody
  4. Sets up a newResp (new response) with newBody
  5. Returns that newResp to the client

Note that depending on how you want to append the script, you can change this logic. Sometimes a script should be loaded in head - you could replace the </body> with </head> or whatever your specific requirement is.

You can view a sample in our playground here.