Robey Lawrence

Running local scripts with HTML buttons

I was curious if it was possible to run local scripts from simply clicking a button on a basic HTML page, as I can think of a few good scenarios for browser based dashboard pages.

This is using Python with Flask to start a tiny local web server, to serve a basic HTML page. The buttons trigger two different basic bash scripts that use osascript commands that change local MacOS settings.

Here is the code used in the app.py file:

from flask import Flask, request, jsonify
import subprocess

app = Flask(__name__)

HTML_PAGE = """
<!DOCTYPE html>
<html>
<head>
    <title>Run Bash Scripts</title>
    <script>
        function runScript(scriptName) {
            fetch('/run-script', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ script: scriptName }),
            })
            .then(response => response.json())
            .then(data => {
                let messageDiv = document.getElementById('message');
                messageDiv.innerText = data.message;
                messageDiv.style.display = 'block';

                setTimeout(function() {
                    messageDiv.style.display = 'none';
                }, 5000);
            });
        }
    </script>
</head>
<body>
    <h2>Run Bash Scripts</h2>
    <button onclick="runScript('Dark Mode')">Switch to Dark Mode</button>
    <button onclick="runScript('Light Mode')">Switch to Light Mode</button>
    <div id="message" style="display:none;"></div>
</body>
</html>
"""

@app.route('/')
def index():
    return HTML_PAGE

@app.route('/run-script', methods=['POST'])
def run_script():
    data = request.get_json()
    script = data['script']
    
    if script == 'Dark Mode':
        subprocess.run(['bash', 'dark_mode.sh'])
    elif script == 'Light Mode':
        subprocess.run(['bash', 'light_mode.sh'])

    return jsonify({'message': f'{script} script executed!'})

if __name__ == '__main__':
    app.run(debug=True)

And here is the code used in the basic bash scripts:

#!/bin/bash

# Switch to Dark Mode
osascript -e 'tell app "System Events" to tell appearance preferences to set dark mode to true'

Tiny Python/Flask app to run local bash scripts with HTML buttons.

— Robey (@robey)2023-11-21T01:46:02.229Z

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.