Chrome extension image change not persisting

Tags: , ,



I’m experimenting around with creating a Chrome extension (Opera actually but I don’t think that matters) that uses two text boxes as input to generate the path to an image to render, but the image never appears.

manifest.json

{
    "manifest_version": 2,

    "name": "Opera Extensions — Getting Started",
    "description": "Sample extension for the “Making your first extension” article",
    "version": "1.0",
    "background": {
        "scripts": ["home.js", "background.js"]
    },

    "permissions": ["tabs"],
    "browser_action": {
        "default_icon": "icon.png",
        "default_title": "Go to Dev.Opera!"
    },
    "web_accessible_resources": ["home.html"]
}

home.html

<html>
<body>

    <form>
        <label for="a">Part 1:</label>
        <input type="text" id="a" name="a"><br><br>
        <label for="b">Part 2:</label>
        <input type="text" id="b" name="b"><br><br>
        <input id="submit" type="submit" value="Go">
    </form>

    <img id="myImg" src="" />

</body>
</html>

<script src="home.js"></script>

home.js

var submit = null;
document.addEventListener("DOMContentLoaded", () => {
    submit = document.getElementById("submit");
    if (submit !== null) {
        submit.addEventListener("click", myFunction);
    }
});

function myFunction() {
    var a = document.getElementById('a').value;
    var b = document.getElementById('b').value;

    if (a !== '' && b !== '') {
        var fileName = "media/" + a + b + ".png";
        var image = document.getElementById("myImg");
        image.src = fileName;
    } else {
        alert('Enter values');
    }
}

The weird thing is that when I debug my code, the correct path does appear when inspecting the element, but once the code finishes debugging the image src reverts back to empty. I also know the path is correct because if I hard code it into the src it does appear.

The first image below shows the HTML during debugging, and the second shows the image that does appear when it is hard coded.

Debugger codeHardcoded image

Any help would be appreciated. Thanks.

Answer

Your form is being submitted and the whole page is being refreshed. In the click listener you need to accept the event parameter and call preventDefault(). Something like this:

submit.addEventListener("click", (e) => {
        e.preventDefault()
        myFunction()
    });

Calling preventDefault will stop the default action of the event from occurring. In this case, the submission of the form. Read all about it here.



Source: stackoverflow