Error loading image on front-side of note using javascript

I am currently working on an addon which adds a new notetype. Right now i am trying to create the design of the front-side of the card which contains javascript. My problem is whenever i try to load an image in javascript using an absolute path to the image file like this: elem.src = "C:\\Users\\name\\AppData\\Roaming\\Anki2\\addons21\\ChessAddon\\user_files\\B.png"; I get an error message saying:

“Not allowed to load local resource: file:///C:/Users/name/AppData/Roaming/Anki2/addons21/myaddon/user_file/B.png”

When using a relative path like this: elem.src = "/user_files/B.png";, asumming the script is run in the root of the addon directory, I get the following error message:

GET htttp://127.0.0.1:63465/user_files/B.png 404 (NOT FOUND).

(Had to add a third t so its not a link and lets me post this. It’s http.)

So either way it doesn’t work. The html file containing the javascript code is in the root of my addon folder and the folder containing the image files is also there and named user_files. This is how my addon folder looks like:
addonFolder

The way I load the Front.html file is like this:

loadHtml

This seems to be working because I can see everything except for the images. Also when I open the Front.html file in a browser everything works fine and the images get loaded.

I have been searching for a solution for hours now. If anyone has any idea on how to load the images or knows what the problem, please let me know. Any help would be greatly appreciated.

See qt/aqt/webview.py:

3 Likes

Thanks for your fast reply! Can this also be used to load images? My Javascript, css and html files are found but whenever I want to load an image into the webview it doesn’t work.
After looking through some more code this morning I got it working by using mw.col.media.add_file(path_to_image) but would be glad to know if there is a different or better way to do it.

Yes, you can load images, sounds, fonts, etc. that way. Here is an example of inserting foo.png from the user_files folder into the qa element each time you flip a card.

from anki.cards import Card
from aqt import gui_hooks, mw

mw.addonManager.setWebExports(__name__, r"user_files/.*")
package_dir = mw.addonManager.addonFromModule(__name__)
js = f"""
<script>
    var img = document.createElement("img");
    img.src = "/_addons/{package_dir}/user_files/foo.png";
    document.getElementById("qa").appendChild(img);
</script>
"""


def on_card_will_show(text: str, card: Card, kind: str) -> str:
    return text + js


gui_hooks.card_will_show.append(on_card_will_show)
3 Likes