Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Flask: play sound after click link but before reload page

When you click link then web browser reloads page and it removes from memory code which should play sound.

You would have to catch link

<a href="javascript:void(0);" onclick="sound('{{item}}')">JAVASCRIPT LINK</a>

play sound and redirect/reload page after sound.

function sound(item) {
    var audio = new Audio('/static/audio_file.mp3');
    audio.onended = function() { window.location.href="/delete/" + item; }
    audio.play();
}

Minimal working example

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
<a href="/delete/{{item}}" onclick="sound()">NORMAL LINK</a><br>

<a href="javascript:void(0);" onclick="sound('{{item}}')">JAVASCRIPT LINK</a>

<script>
function sound(item) {
    //alert("SOUND");
    // create audio 
    var audio = new Audio('/static/audio_file.mp3');
    // reload after audio 
    audio.onended = function() { window.location.href="/delete/" + item; }
    //audio.onended = function() { window.location.reload(); }
    // play audio
    audio.play();
}
</script>
''', item="SomeValue")

app.run() #debug=True 
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury