Detecting a mobile browser with Qt WebAssembly
Solved
Qt for WebAssembly
-
Hello,
I try to make it by checking
screen.orientation
, like here: https://stackoverflow.com/a/14301832/4159530 but it returnstrue
even for the desktop Chrome browser:#include <emscripten.h> #include "widget.h" EM_JS(bool, callMobileCheck, (), { let check = false; if (typeof screen.orientation !== "undefined") { check = true; } return check; }) Widget::Widget(QWidget *parent) : QWidget(parent) { bool result = callMobileCheck(); qDebug() << result; }
-
I think this idea is good: https://stackoverflow.com/a/29509267/4159530
This is my cross-platform solution in Qt C++ for Android, Desktop and WebAssembly:
#ifdef Q_OS_WASM #include <emscripten.h> #endif #include "widget.h" #ifdef Q_OS_WASM EM_JS(bool, isMobile, (), { return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); }) #endif Widget::Widget(QWidget *parent) : QWidget(parent) { bool isMobile = false; #ifdef Q_OS_WASM isMobile = isMobile(); #endif #if defined Q_OS_ANDROID || defined Q_OS_IOS isMobile = true; #endif qDebug() << "isMobile:" << isMobile; }
Don't forget to add
wasm:
here:QT += core gui widgets CONFIG += c++17 wasm: INCLUDEPATH += "C:\emsdk\upstream\emscripten\cache\sysroot\include" SOURCES += \ main.cpp \ widget.cpp HEADERS += \ widget.h
-
-
I think it is better to use
Q_OS_WASM
instead of__EMSCRIPTEN__
I have changed it. -
-
I have replaced the follwing line in the code example above:
#ifdef Q_OS_ANDROID
with this one to detect iOS too:
#if defined Q_OS_ANDROID || defined Q_OS_IOS