Home > Net >  Change innerHTML in the extension
Change innerHTML in the extension

Time:10-10

I am new to js and I am trying to make a simple extension which generates a random number.

document.getElementById("submit").onclick = function() {
  a = document.getElementById("in1").value;
  b = document.getElementById("in2").value;
  document.getElementById("text").innerHTML = `Your num is ${Math.random() * (b - a)   a}`;
};
<body>
  <h1>Generate a random number</h1>
  <br>
  <h2>First number</h2>
  <input id="in1">
  <br>
  <h2>Second number</h2>
  <input id="in2">
  <br>
  <button id="sumbit">Submit</button>
  <h1 id="text">Your num is</h1>

  <script src="popout.js"></script>
</body>

Here is my JSON code:

{
    "name": "Random number",
    "version": "1.0", 
    "description": "Pass", 
    "browser_action":{
        "default_title": "POPOUT.HTML",
        "default_popup": "popout.html"
    },
    "manifest_version": 2,
    "content_scripts": [
        {
          "matches": ["https://*/*"],
          "js": ["popout.js"]
        }
    ]
}

The problem is that whenever I click the button submit I don't get the result. It seems to me that I didn't include something and my fucntion onclick is never called

CodePudding user response:

Change Id="sumbit" to id="submit" and also use let or const before a and b.

CodePudding user response:

I think content_scripts are unnecessary. I think that V3 is better if you start from now, so I rewrote it with V3.

manifest.json

{
  "name": "Random number",
  "version": "1.0",
  "manifest_version": 3,
  "description": "Pass",
  "action": {
    "default_title": "POPOUT.HTML",
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>

<body>
  <h1>Generate a random number</h1>
  <br>
  <h2>First number</h2>
  <input id="in1">
  <br>
  <h2>Second number</h2>
  <input id="in2">
  <br>
  <button id="submit">Submit</button>
  <h1 id="text">Your num is</h1>

  <script src="myscript.js"></script>
</body>

</html>

myscript.js

document.getElementById("submit").onclick = () => {
  const a = document.getElementById("in1").value;
  const b = document.getElementById("in2").value;
  document.getElementById("text").innerHTML = `Your num is ${Math.random() * (b - a)   a}`;
};

  • Related