Trick to bypass inline script restrictions on Chrome extension

I have developed a Chrome extension with a feature that involves looping a list of links into a .div element. Here is the code snippet:

function updateIcd() {

modalIcdLinks.innerHTML = '';
let icdLinks = '';

for (let i = 0; i < icdCodes.length; i++) {

    icdLinks += '<a href="#" onclick="removeIcd('+i+')">'+ icdCodes[i] +' [x]</a><br />'

}

modalIcdLinks.innerHTML = icdLinks;
}

When one of these links is clicked, it should pass the parameter to the removeIcd function in order to remove it from the array.

The issue I am facing is that Chrome extensions do not support inline scripting for security reasons. This means I need to find an alternative way to pass the value (like the array index) to my JavaScript function when a link is clicked without using inline scripting. Any suggestions on how to achieve this?

Answer №1

Implement direct DOM manipulation and create a JavaScript function for handling onclick events:

function updateIcd() {
  const container = document.createDocumentFragment();
  icdCodes.forEach((code, index) => {
    container.appendChild(
      create('a', {
        href: '#',
        onclick: () => removeIcd(index),
        textContent: code + ' [x]',
      }));
    container.appendChild(create('br'));
  });
  modalIcdLinks.textContent = '';
  modalIcdLinks.appendChild(container);
}

function create(element, props) {
  return Object.assign(document.createElement(element), props);
}

The names of DOM properties like textContent or onclick are case-sensitive. They resemble HTML attributes but may contain uppercase letters. To confirm the correct spelling, you can type something like document.body. in the devtools console (remember the dot at the end), use the auto-complete shortcut (Ctrl-Space), type a few characters to see matching properties.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

Encountered an issue with trying to access the 'map' property of an undefined value while using Express and VueJS

Currently, I am in the process of developing a fullstack application utilizing Express, VueJS, and Mongoose. The app functions as a news feed platform. A couple of days ago, I encountered an error which was resolved with the help of your guidance. However, ...

Guide to adding information to a file in Nodejs depending on a condition

Looking for assistance on how to append an annotation (@Circuit(name = backendB)) to a file if the "createEvent" name exists and the annotation is not already present. I am unsure of the process, so any help on checking and appending using streams would ...

Exploring the Node.js view object within a function and delving into the reasons why a property of

As a beginner in programming, I am seeking tips on how to effectively learn node.js. Currently, I am utilizing the "Learning Behavior Driven Development with JavaScript" book for my learning journey. I would greatly appreciate any advice on how to view ob ...

Steps for Creating an Animation Tool based on the Prototype:

One question that recently came up was: What is the best approach to tackling this issue? Developing a tool that enables designers to customize animations. To make this process easier, it is essential to create an AnimationSequence using JavaScript that ca ...

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

TypeScript and Next.js failing to properly verify function parameters/arguments

I'm currently tackling a project involving typescript & next.js, and I've run into an issue where function argument types aren't being checked as expected. Below is a snippet of code that illustrates the problem. Despite my expectation ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

What significance does it hold for Mocha's `before()` if the function passed requires parameters or not?

In one part of my code, I have a describe block with before(a) inside. The function a originally looks like this: function a() { return chai.request(app) ... .then(res => { res.blah.should.blah; return Promise.resolve(); }); ...

The JSON output is throwing an error because it is unable to access the property '0' since it is

Trying to convert JSON data into an HTML table, I encountered the following error: "Cannot read property '0' of undefined" <?php $idmatchs = "bGdzkiUVu,bCrAvXQpO,b4I6WYnGB,bMgwck80h"; $exploded = explode(",", $idmatchs); $count = count( ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

Using Vuetify to display text fields in a single row

Check out this Vue component template (View it on CODEPEN): <div class="some-class"> <v-form > <v-container @click="someMethod()"> <v-row> <v-col cols="3" sm="3" v-for="p in placeholders" ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: Tr ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

modifying the appearance of the play button through a JavaScript event without directly altering it

I am currently working on building a music player from scratch using HTML, CSS, and JavaScript only. To store the list of songs, I have created an array named "songs" with details such as song name, file path, and cover image path. let songs = [ {songNa ...

Development is hindered due to Cors policy restricting access to the localhost webapp

Currently, I am working on developing a web application and an API simultaneously, but I'm facing some issues with CORS blocking. This concept is relatively new to me, and I'm eager to improve my understanding. Firstly, I have set up an Express ...

Issue encountered with AJAX request using JavaScript and Express

I'm brand new to this and have been searching online for a solution, but I can't seem to figure it out. It's possible that I'm making a basic mistake, so any assistance would be greatly appreciated. I'm trying to create a simple f ...

Creating numerous hash codes from a single data flow using Crypto in Node.js

Currently, I am developing a Node.js application where the readable stream from a child process' output is being piped into a writable stream from a Crypto module to generate four hash values (md5, sha1, sha256, and sha512). However, the challenge ari ...