Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inject a script into a HTML response through Akamai?

Tags:

cdn

akamai

This is a bit of an edge use case, but I want to inject some JavaScript into a page without making a code change at the back end. So I'm wondering if there is a rule I can set for a specific route at Akamai, that would inject or add a <script> tag into the HTML body. I could host the external JavaScript file, but I just don't want to have to make a change at the origin to the HTML response.

like image 300
Visvamba Nathan Avatar asked Nov 01 '25 19:11

Visvamba Nathan


1 Answers

In Akamai, HTML content can be modified with the use of EdgeWorkers. For example, the find-replace-stream example can be modified to inject a <script> tag at the end of the tag.

export function responseProvider(request) {
  // Get text to be searched for and new replacement text from Property Manager variables in the request object.
  const tosearchfor = '</head>';
  const newtext = request.getVariable('<script>......</script></head>');
  // Must have a number larger than 0 to allow and limit replacements counts
  const howManyReplacements = 1;

  return httpRequest(`${request.scheme}://${request.host}${request.url}`).then(response => {
    return createResponse(
      response.status,
      getSafeResponseHeaders(response.getHeaders()),
      response.body
      .pipeThrough(new TextDecoderStream())
      .pipeThrough(new FindAndReplaceStream(tosearchfor, newtext, howManyReplacements))
      .pipeThrough(new TextEncoderStream())
    );
  });
}
like image 176
Josh Avatar answered Nov 03 '25 23:11

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!