cdnakamai

Is it possible to inject a script into a HTML response through 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.


Solution

  • 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())
        );
      });
    }