Search code examples
javascriptcssiframeflaskmobile

Check if device is mobile in Flask


I am displaying a list of PDF files using Flask and Materialize

<table class="highlight responsive-table">
    <thead>
        <th class="left-align"><i class="material-icons">call</i></th>
        <th class="left-align"><i class="material-icons">email</i></th>
        <th class="center-align"><i class="material-icons">picture_as_pdf</i></th>
    </thead>
    <tbody>
        {% for doc in docs %}
            <tr>
                <td>{{doc.phone if doc.phone}}</td>
                <td>{{doc.email if doc.email}}</td>
                <td>
                    <a href="#modal{{loop.index}}" class="modal-trigger"><i class="material-icons">open</i> Ouvrir</a>
                </td>
            </tr>
            <div class="modal" id="modal{{loop.index}}">
                <iframe src="/cv/{{doc.name}}" scrolling="no" width="100%" height="100%"></iframe>
            </div>
        {% endfor %}
    </tbody>
</table> 

enter image description here

The PDF is displayed in a modal window using the iframe.

enter image description here

When I open the page in mobile, and instead of showing the PDF in modal, it prompts me to download the pdf as if I was trying to download it directly. As I am using a for loop in Flask, I get a download prompt for each PDF. I would like to know if there's a way to check if the user agent is mobile, so that if that's the case, then I will display a link to the pdf instead of the modal window.


Solution

  • I solved the problem using Flask-Mobility. It allows to detect if the device is mobile

    from flask_mobility import Mobility
    
    ...
    
    app = Flask(__name__)
    Mobility(app)
    
    ...
    
    {% for doc in docs %}
        <tr>
            <td>{{doc.phone if doc.phone}}</td>
            <td>{{doc.email if doc.email}}</td>
            <td>
                {% if request.MOBILE %}
                    <a href="/cv/{{doc.name}}" target="_blank"><i class="material-icons">open</i> Ouvrir</a>
                {% else %}
                    <div class="modal" id="modal{{loop.index}}">
                        <iframe src="/cv/{{doc.name}}" scrolling="no" width="100%" height="100%"></iframe>
                    </div>
                    <a href="#modal{{loop.index}}" class="modal-trigger"><i class="material-icons">open</i> Ouvrir</a>
                {% endif %}
           </td>
        </tr>
    {% endfor %}