google-chrome-extension

How to perform onclick action on functions with variables in Chrome Extensions?


I have the following code which the hyperlink will be generated dynamically. The hyperlinks can be generated successfully.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="styles.css" />
    <title>Timely</title>
  </head>
  <body id=settingbg>
  <a href=index.html>Home</a>
    <div id="stopping"><div id=stopitem></div>
  </body>
  <script src="setting.js"></script>
</html>

script.js

let stopping = document.getElementById("stopping");

showstop();

function showstop(){
    chrome.storage.local.get(['stops'], function(result) {
        let stopsp = (result.stops).split(",");
        for(i=0;i<stopsp.length;i++){
            stopping.innerHTML += "<div id=stopitem><a href='#' id='linkPassValue' data-value='"+stopsp[i]+"'>"+stopsp[i]+"</a></div>";
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('#linkPassValue')?.addEventListener('click', function(e) {
    e.preventDefault();
    const value = this.getAttribute('data-value');
    alert(value);
  });
});

However, the onclick action is not worked once hyperlinks generated. Could anyone help me to achieve this? Thank you.


Solution

  • Nah ... dont worry about all of that. innerhtml is fine ... just:

    1. Use classes instead of ids for generated content (bad form to generate multiple items with the same id).

    2. The key is going to be to create the event handler during (right after) content gen

    One function should get you there just fine:

    function showstop() {
      chrome.storage.local.get(['stops'], function(result) {
        let stopsp = result.stops.split(",");
        const container = document.getElementById('stopping');
        container.innerHTML = ''; // Clear previous content if needed
    
        for (let i = 0; i < stopsp.length; i++) {
          // Use class instead of duplicate IDs
          container.innerHTML += "<div class='stopitem'><a href='#' class='linkPassValue' data-value='" + stopsp[i] + "'>" + stopsp[i] + "</a></div>";
        }
      });
    
      document.querySelector('#stopping').addEventListener('click', function(event) {
        event.preventDefault();
    
        const target = event.target;
    
        if (target.classList.contains('linkPassValue')) {
          const value = target.getAttribute('data-value');
          alert(value);
        }
      });
    }
    
    showstop();