简体   繁体   中英

Chrome extension image change not persisting

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.

调试器代码 硬编码图像

Any help would be appreciated. Thanks.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM