Playwright test fails when using waitForResponse with gql query

I think i am having a race condition in my test where UI is faster then API calls, which is leading for elements to be not found since its never in different state, this happening only in the pipeline and working fine in my local.

I did some debugging and found out on local all API calls return response before the UI is rendered but this is not the case in test in pipeline

My code is something like below

   const gqlResponsePromise = this.page.waitForResponse(response =>
    response.url().includes('ActiveIntegrationsQuery') && response.status() === 200
  );

  
  await this.page.click('#button');

 
  await gqlResponsePromise;

///

Next steps

i am having two issues.

  1. since its a gpl query all the urls are same like http://localhost:5000/api/dev/graphql

so instead i am not sure what to give in the .includes currently i am giving this name ActiveIntegrationsQuery because i need to wait for this API responseenter image description here before proceeding

  1. The test runs out of time probably because its unable to find the url which i am giving above.

error shown when running discord bot; DiscordAPIError[50035]: Invalid Form Body

yo, okay so i’m coding a discord bot with javascript, and i got quite far before i was hit with an error i got no clue what to do about;
(no idea where the error is, so i’ve given three files);

my handleCommands.js code;

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');

module.exports = (client) => {
    client.handleCommands = async() => {
        const commandFolders = fs.readdirSync('./src/commands');
        for (const folder of commandFolders) {
            const commandFiles = fs
                .readdirSync(`./src/commands/${folder}`)
                .filter((file) => file.endsWith(".js"));

            const { commands, commandArray } = client;
            for (const file of commandFiles) {
                const command = require(`../../commands/${folder}/${file}`);
                commands.set(command.data.name, command);
                commandArray.push(command, command.data.toJSON());
                console.log(`Command: ${command.data.name} has been passed through the handler.`)
            }
        }

        const clientId = 'no peaking';
        const guildId = 'also no peaking';
        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');

            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId), {
                    body: client.commandArray
            });

            console.log('Successfully reloaded application (/) commands.');
        } catch(error) {
            console.error(error);
        }
    };
};

my ping.js file;

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('ping')
        .setDescription('Return my ping!'),
    async execute(interaction, client) {
        const message = await interaction.deferReply({
            fetchReply: true
        });

        const newMessage = `API Latency: ${client.ws.ping}nClient Ping: ${message.createdTimestamp - interaction.createdTimestamp}`
        await interaction.editReply({
            content: newMessage
        });
    }
}

and my interactionCreate.js file;

module.exports = {
    name: "interactionCreate",
    async execute(interaction, client) {
        if(interaction.isChatInputCommand()) {
            const { commands } = client;
            const { commandName } = interaction;
            const command = commands.get(commandName);
            if(!command) return;

            try {
                await command.execute(interaction, client);
            } catch (error) {
                console.error(error);
                await interaction.reply({
                    content: `Something went wrong while executing this command...`,
                    ephemeral:true
                });
            }
        }
    },
};

the error that i’m getting;

Command: ping has been passed through the handler.
Started refreshing application (/) commands.
DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
    at handleErrors (C:[email protected]:722:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (C:[email protected]:1120:23)
    at async SequentialHandler.queueRequest (C:[email protected]:953:14)
    at async _REST.request (C:[email protected]:1266:22)
    at async client.handleCommands (C:UsersINTELDocumentsSHADOWsrcfunctionshandlershandleCommands.js:28:13) {
  requestBody: { files: undefined, json: [ [Object], [Object] ] },      
  rawError: {
    message: 'Invalid Form Body',
    code: 50035,
    errors: { '0': [Object] }
  },
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v9/applications/1202951270202347550/guilds/1202952385195155546/commands'
}
Ready!!! SHADOW.#5922 is logged in and online.

IF ANYONE CAN HELP IN ANY WAY, THAT WOULD BE SO APPRECIATED – a coding noob.

i tried a LOT of things (going through files for typos, changing code around, etc.) but nothing’s worked so PLEASE HELP 🙁

Node-mailer: Problem with rendering node mail images in the body; bug ID: 146469

There is an intermediate problem with some mails having a partially rendered image that comes in the mail body using nodemailer.

htmlForMailBody += '<div>' + txt.split("$reportname").join(reportName).split("$sddate").join(reportStartDate).split("$eddate").join(reportEndDate).split("$genDateTime").join(getDateForReports()) + '</div><br><div> URL = <a href=' + genURLFile + '>' + genURLFile + '</a></div><br>';
         if (chartImagePathArr != undefined && chartImagePathArr.length > 0) {
             htmlForMailBody += '<div>';
             for (let i = 0; i < chartImagePathArr.length; i++) {
                 let chartImgPathObj = chartImagePathArr[i]['imgPath'];
                 let obj = {
                     path: ipPort + chartImgPathObj,
                     cid: 'chartImage_' + i
                 }
                 attachmentsArray.push(obj);
                 chartImagePathArr[i].rptSetName = undoReplaceName(chartImagePathArr[i].rptSetName) + "...";

                 if (chartImagePathArr.length > 3) {
                     if (chartImagePathArr.length % 2 == 0)
                         htmlForMailBody += '<div style='padding:3px;width:50%;box-sizing:border-box;float:left'><label style='background:#081f3c;color:#fff;font-size:12px;padding:2px;text-overflow:ellipsis;white-space:nowrap;display:inline-block;overflow:hidden;width:100%'>' + chartImagePathArr[i].rptSetName + '</label><img src=cid:chartImage_' + i + ' ></div>';
                     else {
                         if (i == chartImagePathArr.length - 1)
                             htmlForMailBody += '<div style='padding:3px;box-sizing:border-box'><label style='background:#081f3c;color:#fff;font-size:12px;padding:2px;text-overflow:ellipsis;white-space:nowrap;display:inline-block;overflow:hidden;width:100%'>' + chartImagePathArr[i].rptSetName + '</label><img src=cid:chartImage_' + i + ' ></div>';
                         else
                             htmlForMailBody += '<div style='padding:3px;width:50%;box-sizing:border-box;float:left'><label style='background:#081f3c;color:#fff;font-size:12px;padding:2px;text-overflow:ellipsis;white-space:nowrap;display:inline-block;overflow:hidden;width:100%'>' + chartImagePathArr[i].rptSetName + '</label><img src=cid:chartImage_' + i + '></div>';
                     }

                 } else
                     htmlForMailBody += '<div style='padding:3px;box-sizing:border-box'><label style='background:#081f3c;color:#fff;font-size:12px;padding:2px;text-overflow:ellipsis;white-space:nowrap;display:inline-block;overflow:hidden;width:100%'>' + chartImagePathArr[i].rptSetName + '</label><img src=cid:chartImage_' + i + '></div>';

             }
             htmlForMailBody += '</div>';
         }

         if (attachmentsArray.length > 0) {
             schedulerLog("Creating Mail Option with attachments", 1);
             mailOptions = {
                 html: htmlForMailBody,
                 from: global.mailConfInfo['user'], // sender address
                 to: mailObj.to, // list of receivers
                 subject: sub.split("$reportname").join(reportName).split("$sddate").join(reportStartDate).split("$eddate").join(reportEndDate).split("$genDateTime").join(getDateForReports()), // Subject line
                 attachments: attachmentsArray
             };
         } else {
             schedulerLog("Creating Mail Option without attachments", 1);
             mailOptions = {
                 html: htmlForMailBody,
                 from: global.mailConfInfo['user'], // sender address
                 to: mailObj.to, // list of receivers
                 subject: sub.split("$reportname").join(reportName).split("$sddate").join(reportStartDate).split("$eddate").join(reportEndDate).split("$genDateTime").join(getDateForReports()) // Subject line
             };
         }

         let msStartDate = new Date();
         console.error("send mail StartDate time for checing delay", msStartDate);

         msStartDate = new Date();
         console.error("setTimeout checing delay time :", msStartDate);
         transporter.sendMail(mailOptions, function (error, info) {
             try {
                 msStartDate = new Date();
                 console.error("setTimeout transporter try block on send mail delay time :", msStartDate);
                 if (typeOfReport == 2) {
                     const fs = require('fs');
                     fs.unlinkSync(filename);  //Removing tar file of HTML Report
                 }
             } catch (err) {
                 console.error("setTimeout transporter catch block on send mail delay time :", msStartDate);
                 schedulerLog("Error on deleting tar file of html report with error Info == " + err, 1);
             }
             if (error) {
                 return schedulerLog("Error in sending mail, error info is = " + JSON.stringify(error), 2);
             }
             schedulerLog("Mail is sent with error Info == " + JSON.stringify(error), 2);
             schedulerLog("Mail is sent with success Info == " + JSON.stringify(info), 1);
         });

Note : This problem won’t keep coming up. Sometimes it does work.

we want some solution for this and want to know why this issue is comming in mid of mail scheduling.

what is “Import trace for requested module” and how to fix

this is my first time in the site, so sorry for bad question post, so, my app was working normally, no problems, today when i tried to run npm run dev (i didnt change anything just run it) i got this wierd error, that even the terminal wasnt enough to fit it , anyone have any idea ?

https://gist.github.com/Enkai0110/2336a8fe345f17cdd0221c4661a19785

i cleared browser history and cache, deleted the next. folder, but nothing happen

Routing in AngularJS is not working for me

<script>
var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider){
    $routeProvider.when('/dataBinding', {
        template: `
          <div ng-controller="myCtrl">
            <h3>Data Binding controller</h3>
            <input type="text" ng-model="firstName">
            <input type="text" ng-model="lastName">
            <br><br>
            {{ firstName + ' ' + lastName }}
          </div>
        `,
        controller: 'myCtrl'
      }).when('/httpapi', {
        template: `
          <div ng-controller="apiCtrl">
            <h3>$https API Controller</h3>
            <p>A fact From API: {{ reqCode }}</p>
          </div>
        `,
        controller: 'apiCtrl'
      })
      .when('/cusService', {
        template: `
          <div ng-controller="customeServiceCtrl">
            <h3>Custom Service API call Controller</h3>
            <p>Genderize API using Custom Service: {{ cusserviceData }}</p>
          </div>
        `,
        controller: 'customeServiceCtrl'
      });
})

app.controller('apiCtrl',function($scope,$http){
    $http({
      method:'get',
      url:'https://catfact.ninja/fact'  
    }).then(function(response){
      
      $scope.reqCode = response.data.fact;
    })
})


app.controller('customeServiceCtrl',function($scope,myService){
        $scope.myData = {"email": "[email protected]","password": "cityslicka"};
    myService.resData($scope.myData).then(function(token) {
      $scope.cusserviceData = token;
    })
})
</script>
<div>
  <a href="#/dataBinding">Data Binding</a>
  <a href="#/list">List</a>
  <a href="#/httpapi">$https API</a>
  <a href="#/cusService">Custom Service API call</a>
</div>
<div ng-view></div>

routing is not working in my file. i have used all the cdn aswell. other than routing config all are working fine, like services, controllers and custom directives, etc,. Please someone find the issue and rectify me . iam new to angular js.

Playwright automation script doesn’t do `async…await` in `for..loop` properly for `/signup` page?

So I’m trying to automate rate-limit requests with playwright automation script.

But the problem is it keeps signing up for [email protected] email & therefore keeps giving Email already used error.

I thought I am using async...await right with for...loop but apparently not.

import { chromium } from 'playwright'

async function main() {
  const browser = await chromium.launch({ headless: false })

  const page = await browser.newPage()
  for (let i = 0; i < 20; i++) {
    await page.goto('http://localhost:3000/signup')
    await page.waitForLoadState('domcontentloaded')

    await page.fill('input[name="email"]', `test${i}@example.com`)
    await page.click('button[type="submit"]')

    await page.waitForURL('http://localhost:3000/verify-email')
    // await page.waitForSelector('#verify-email-form', {
    //   state: 'visible',
    //   timeout: 0,
    // })

    console.log(i)
  }

  await page.close()
  await browser.close()
}

main()

I tried the commented code too above but that doesn’t work either.

My server script gives this:

{ email: '[email protected]' }
{ user: [], unique: true }
{ email: '[email protected]' }
{
  user: [
    {
      id: '01HNPK1GRM5ZHWXZBV1K2R3A9B',
      email: '[email protected]',
      emailVerified: 0
    }
  ],
  unique: false
}

It checks for unique email so first time it gives unique: true but next time it gives unique: true.

This shouldn’t happen as I’m using for...loop with async...await.

It should look like:

{ email: '[email protected]' }
{ user: [], unique: true }
{ email: '[email protected]' }
{ user: [], unique: true }

What am I doing wrong?

i made a filter in my page to segregate it from the rest. (html,css,js,jquery,isotope)

it’s working fine but the problem is my responsiveness of my page is not working as i expected and also my search is not working properly.it’s giving the results but the problem is the card that i searched is not appearing on the top.it’s fixed at its initial position.

i thought the filter would work fine as i only added 1 div in the html (https://i.stack.imgur.com/oo5o5.jpg)](https://i.stack.imgur.com/W02iv.jpg)

Expected the value to be an object, but received string instead on discordjs v14

So i tried to take the server info data with the owner id
but when i run the command it gives me an error

“Expected the value to be an object, but received string instead
|
| Received:
| | ‘<a:yes:962966293764505620> Server Owner: <@710720629002862632>'”

Code:

    run: async (client, interaction, args) => {
        let msg = await interaction.reply(`Checking..`);
        let boosts = interaction.guild.premiumSubscriptionCount;
        const ar = ("<a:yes:962966293764505620>")
        let myguild = interaction.guild;
        const members = interaction.guild.members.cache;
        var boostlevel = 0;
      if (boosts >= 2) boostlevel = "1";
      if (boosts >= 7) boostlevel = "2";
      if (boosts >= 14) boostlevel = "3 / ∞";
      let maxbitrate = 96000;
      if (boosts >= 2) maxbitrate = 128000;
      if (boosts >= 7) maxbitrate = 256000;
      if (boosts >= 14) maxbitrate = 384000;
      interaction.guild.owner = await interaction.guild.fetchOwner().then(m => m.user).catch(() => {})

      const emb = new EmbedBuilder()
      .setColor("Aqua")
      .setTitle(`Server info of ${interaction.guild.name}`)
      
        .setImage(interaction.guild.bannerURL({size: 4096}))
        .addFields(`${ar} Server Owner: ${interaction.guild.owner}`)
    .setThumbnail(client.user.displayAvatarURL({ dynamic : true }))
    .setFooter({
        text: `Command Requested by: ${interaction.user.tag}`,
        iconURL: interaction.user.displayAvatarURL(),
      })

    setTimeout(() => {
        msg.edit({ content: ` `, embeds: [emb] });
      }, 500);
    },
    };

I Tried a few solution online and still doesnt help

Two way communication between web and android [duplicate]

im trying to send a push notification from chrome plugin using javascript to android device. so when user login using the plugin, they will be authenticated using Firebase Authentication. then a approval notification should be sent to their android device. after clicking “approve” a list of password will be displayed in the plugin

I tried using Firebase Cloud Messaging. From the console, I tried testing it using the device token and the notification indeed went through. But im not sure how to send it from the plugin to the android device

Text change on click – javascript

I have a custom slide out modal form. Im tryign to change to “send message” button text onlick. I have 2 codes that Im trying to combine to acheiev this, but I am successful 🙁 I have this code which appears after clicking the button, but it only loads under the button –

<script>
const form = document.getElementById('form');
const result = document.getElementById('result');

form.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(form);
const object = Object.fromEntries(formData);
const json = JSON.stringify(object);
result.innerHTML = "Sending, please wait..."

fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: json
    })
    .then(async (response) => {
        let json = await response.json();
        if (response.status == 200) {
            result.innerHTML = json.message;
        } else {
            console.log(response);
            result.innerHTML = json.message;
        }
    })
    .catch(error => {
        console.log(error);
        result.innerHTML = "Oops, something's not right...";
    })
    .then(function() {
        form.reset();
        setTimeout(() => {
            result.style.display = "none";
        }, 3000);
    });
});
</script>

Now I have this code that only changes the text onclick, but not functional like the 1st script code –

<input 
     class="submit"
     id="buttonInput" 
     type="button" 
     value="Send message" />
<script>
document.getElementById("buttonInput").addEventListener(
"click",
function(event) {
if (event.target.value === "Send message") {
  event.target.value = "Message sent!";
} else {
  event.target.value = "Send message";
}
},
false
);

Hope this makes sense lol, i am a noob. Anyhow, how can I get both code combined to work. essentially I want the button to chnage text and show the loading then message sent like the first code. So, “Send message”, then “Sending, please wait…”, then “Message sent successfully”?

JS is alien language to me 🙂

How to remove comments from sourcemap created with Rollup and terser for web app javascript bundle?

How can I configure Rollup and it’s terser plugin to create a sourcemap for my web app’s minified javascript bundle, that doesn’t have any of my javascript source code comments? I am using terser to minify my bundle, so I also need to generate a sourcemap to aid in debugging in browser dev tools. The below configuration does successfully produce a ‘main.bundle.js’ bundle and a ‘main.bundle.js.map’ sourcemap file, but I can’t seem to find an option on the Rollup sourcemap docs to remove comments.

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';

export default [
    {
        input: './src/js/main.js',
        output: {
            file: './dist/main.bundle.js',
            format: 'iife',
            name: 'mainjs',
            sourcemap: true
        },
        treeshake: {
            moduleSideEffects: false
        },
        plugins: [
            resolve(),
            terser()
        ]
    }
]

I’ve tried configuring terser like the following, but I get a pretty nondescript error message of: [!] (plugin terser) Error: Minify worker stopped with exit code 1

terser({
    sourceMap: {
        comments: false
    }
})

Issue with Custom WooCommerce Variable Product Attributes dropdown name

Hi I am building a website in woocommerce.

I have made a custom single-product page, as I wanted to style the page.
I have created a childtheme, within this childtheme.

The structure looks like this

#child-theme
|-- functions.php
|-- woocommerce.php
|-- woocommerce
|   |-- add-to-cart
|       |-- variable.php
|-- js
    |-- custom-select-script.js

I have created a varaible product and made attributes and gave them names, like:

name: “choose a price” and values 25 | 50 | 75 | 100
name: “choose a card” and values card1 | card2 | card 3

I want the get this name values as the default value for the generated dropdown, like this

<select name="choose-a-price" id="choose-a-price">
  <option value="">--Choose a Price--</option>
  <option value="kind-1">K-1</option>
  <option value="kind-2">k-2</option>
  <option value="kind-3">k-3</option>
  <option value="kind-4">k-4</option>
</select>

but I am getting all the time;

<select name="choose-a-price" id="choose-a-price">
  <option value="">--Choose a option--</option>
  <option value="kind-1">K-1</option>
  <option value="kind-2">k-2</option>
  <option value="kind-3">k-3</option>
  <option value="kind-4">k-4</option>
</select> 

This my variable.php and with the echo ($attribute_name), I see the name attributes,
but somehow not getting them loaded in the dropdown.

This is variable.php

/**
 * Variable product add to cart
 *
 * This template can be overridden by copying it to kaon-child/woocommerce/single-product/add-to-cart/variable.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see https://woo.com/document/template-structure/
 * @package WooCommerceTemplates
 * @version 6.1.0
 */

defined( 'ABSPATH' ) || exit;

global $product;

$attribute_keys  = array_keys( $attributes );
$variations_json = wp_json_encode( $available_variations );
$variations_attr = function_exists( 'wc_esc_json' ) ? wc_esc_json( $variations_json ) : _wp_specialchars( $variations_json, ENT_QUOTES, 'UTF-8', true );

do_action( 'woocommerce_before_add_to_cart_form' ); ?>

<form class="variations_form cart" action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo $variations_attr; // WPCS: XSS ok. ?>">
    <?php do_action( 'woocommerce_before_variations_form' ); ?>

    <?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
        <p class="stock out-of-stock"><?php echo esc_html( apply_filters( 'woocommerce_out_of_stock_message', __( 'Dit product is op dit moment niet meer beschikbaar.', 'woocommerce' ) ) ); ?></p>
    <?php else : ?>
        <table class="variations" cellspacing="0" role="presentation">
            <tbody>
            <?php foreach ( array_keys( $attributes ) as $attribute_name ) : ?>
    <tr>
        <th class="label"><label for="<?php echo esc_attr( sanitize_title( $attribute_name ) ); ?>"><?php echo wc_attribute_label( $attribute_name ); // WPCS: XSS ok. ?></label></th>
        <td class="value">
            <?php
                wc_dropdown_variation_attribute_options(
                    array(
                        'options'   => array_merge( array( '' => wc_attribute_label( $attribute_name ) ), $attributes[ $attribute_name ] ),
                        'attribute' => $attribute_name,
                        'product'   => $product,
                    )
                );
                echo ($attribute_name);
                echo end( $attribute_keys ) === $attribute_name ? wp_kses_post( apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . esc_html__( 'Clear', 'woocommerce' ) . '</a>' ) ) : '';
            ?>
        </td>
    </tr>
<?php endforeach; ?>

            </tbody>
        </table>
        <?php do_action( 'woocommerce_after_variations_table' ); ?>

        <div class="single_variation_wrap">
            <?php
                /**
                 * Hook: woocommerce_before_single_variation.
                 */
                do_action( 'woocommerce_before_single_variation' );

                /**
                 * Hook: woocommerce_single_variation. Used to output the cart button and placeholder for variation data.
                 *
                 * @since 2.4.0
                 * @hooked woocommerce_single_variation - 10 Empty div for variation data.
                 * @hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
                 */
                do_action( 'woocommerce_single_variation' );

                /**
                 * Hook: woocommerce_after_single_variation.
                 */
                do_action( 'woocommerce_after_single_variation' );
            ?>
        </div>
    <?php endif; ?>

    <?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>

<?php
do_action( 'woocommerce_after_add_to_cart_form' );

I have tried many js, with wp filters and a lot of reading, but cant get it working.
thanks, for helping.
B.

How to automatically attach header in all http requests from client side javascript?

Im looking for a way in javascript, to automatically attach a header to any http requests the page makes wheather its static file assets or api calls, etc… I read in some other posts like these, that using a service worker could help, but I couldn’t get it working for me. Also the server I make requests to, allows CORS to the server I’m making requests from.

serviceworker is it possible to add headers to url request

How to intercept all http requests including form submits

Adding custom headers in Javascript for all http requests

my html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="robots" content="noindex">
    <meta name="theme-color" content="#6E2D91">
    <meta name="description" content="Sample Web App">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="app"></div>
    <script>
      if ('serviceWorker' in navigator) { 
        window.addEventListener('load', function() {   
          navigator.serviceWorker.register('/serviceworker.js').then(
            function(registration) { 
              // Registration was successful
              console.log('ServiceWorker registration successful with scope: ', registration.scope); }, 
            function(err) { 
              // registration failed :( 
              console.log('ServiceWorker registration failed: ', err); 
            }); 
        });
      }

      setTimeout(() => {
        fetch("https://data.global");
      }, 5000);
      </script>
  </body>
</html>

my service worker

self.addEventListener('fetch', event => {
    event.respondWith(customHeaderRequestFetch(event))
});

function customHeaderRequestFetch(event) {
    // decide for yourself which values you provide to mode and credentials

    // Copy existing headers
    const headers = new Headers(event.request.headers);

    // Set a new header
    headers.set('x-my-custom-header', 'The Most Amazing Header Ever');
    // Delete a header
    headers.delete('x-request');

    const newRequest = new Request(event.request, {
        mode: 'cors',
        credentials: 'omit',
        headers: headers
    })
    return fetch(newRequest)
}

You can see I am making a fetch call 5 seconds later. I expect it to get my custom header when sending out. If I were to inject into the DOM a tag and set a source, or embed a huge html string with script tags, link tags, etc… I would expect all the http requests to get their static content to have the header on it. But currently it does not attach the header.

How can I get this to work?