Hide a script from a mobile browser - mobile

I'm trying to hide a script from running when a mobile devise is detected.
I have tried a similar answer that was on another post but that did not work.
I'm simply trying to hide a script like:
< ..script src="js/mydesktop-script.js"><../script>
from mobile devises - since it does not render correct but I want to show it on your regular desktop
Thanks

You can use the DetectMobileBrowsers library (located here) for mobile detection. At that point, you may use a function such as the one below to have your script not be used on mobile devices (the library is kind of embedded in the code).
var check = false;
//if the user is on a mobile device, check = true
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true})(navigator.userAgent || navigator.vendor || window.opera);
if (!check) {
//user is not on a mobile device
//render your external script here
}

Use mobile detection function that's the easiest and than use it in your mydesktop-script.js to disable execution.
function detectmob() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
Or you can check it server side and just don't attach the js to the html.
Server side detection of mobile devices is done or in whatever language you have your app written or for example you can use varnish + esi. Virtually planty of ways to achieve that.
But as I said the easiest is to detect the device in your script and disable part of your script based on detection result.

Related

NextJS SSR in Capacitor

we use Next.js with server-side rendering (SSR) and we'd like to wrap our app with Capacitor.js so that we can ship it to both Android and iOS devices. Sadly, this only seems to be possible when using static site generation (SSG) and I cannot find anything on how to even attempt to make SSR work.
A couple of threads seem to hint that this is possible: How to package a hosted web app with Ionic Capacitor (not sure what type of rendering is used here) and https://github.com/MicrosoftDocs/cordova-docs/blob/master/articles/getting-started/create-a-hosted-app.md (this was for Cordova). I have never used Nuxt.js before but some hints that it could be possible with that framework as well here: Using Capacitor 3 with Nuxtjs SSR
Essentially, is it possible to use Capacitor's Webview to display a hosted app instead of having to first build it statically? Could this be something that Capacitor 3 now allows?
Should this be impossible, what would be your recommendation for having a mobile app knowing that we have built our web (and mobile responsive) product in Next.js, with heavy usage of getServerSideProps (i.e. SSR). Any help would be greatly appreciated.
I am currently investigating the same.
Looking to wrap an existing responsive web application based on nextjs using SSR.
in this blog I read in the comments that you can essentially point capacitor to any existing URL (so also your already running website).
I have not tested it though yet. My biggest questions right now would be:
Could we still use native functions (such as push notifications, which is one of the main reasons of bundling it as an app) then? problably would need to integrate the required libs in my existing web app and check if we are running in capacitor environment somehow.
How does Apple handle such cases upon submissions? I have read that they do reject apps that mainly just wrap existing web sites without offering any app-like advantages.
I managed to do it in react and accomplish it in next in react I had to find injected native-bridge.js which is in npm package #capacitor/android/capacitor/src/main/java/com/getcapacitor/Bridge.java
in the function below and after coping output of the below function I had to disable bridgeJS or if you want the whole function
private JSInjector getJSInjector() {
try {
String globalJS = JSExport.getGlobalJS(context, config.isLoggingEnabled(), isDevMode());
String bridgeJS = "";
// String bridgeJS = JSExport.getBridgeJS(context);
String pluginJS = JSExport.getPluginJS(plugins.values());
String cordovaJS = JSExport.getCordovaJS(context);
String cordovaPluginsJS = JSExport.getCordovaPluginJS(context);
String cordovaPluginsFileJS = JSExport.getCordovaPluginsFileJS(context);
String localUrlJS = "window.WEBVIEW_SERVER_URL = '" + localUrl + "';";
return new JSInjector(globalJS, bridgeJS, pluginJS, cordovaJS, cordovaPluginsJS, cordovaPluginsFileJS, localUrlJS);
} catch (Exception ex) {
Logger.error("Unable to export Capacitor JS. App will not function!", ex);
}
return null;
}
in my js files then I import it which is hard but works
const script = document.createElement('script')
script.onload = rendertodom
script.onerror = rendertodom
script.src = '/native-bridge.js'
document.body.append(script)
function rendertodom () {
import('./App').then(({default:App})=> {
ReactDOM.render(
<App/>,
document.getElementById('root')
)
})
}
the struggling part in next is rendering dynamically where a plugin is needed like the app above or importing native bridge if on native before importing rest of app
I use a function for knowing its android from capacitor which I can't do before native so function is in index
if(isNativ(window)) load capcitor // sudo code from real code above
const isNative = (win) => {
let _a, _b;
if (win === null || win === void 0 ? void 0 : win.androidBridge) {
return true;
}
else return !!((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge);
};

Codename One - Lock screen orientation in the Javascript port

Assuming that my Codename One web-app is supposed to run on a mobile device, I tried to lock its orientation to portrait.
My problem is that the following build hint doesn't force the use of a web-app in portrait mode:
javascript.manifest.orientation=portrait
Am I missing something?
I also tried the following native interface, without success:
(function (exports) {
var o = {};
o.lockPortraitOrientation_ = function (callback) {
// Screen Orientation API, https://w3c.github.io/screen-orientation/#examples
screen.orientation.lock('portrait');
callback.complete();
};
o.isSupported_ = function (callback) {
callback.complete(true);
};
exports.cool_teammate_apps_frontend_NativeUtilities = o;
})(cn1_get_native_interfaces());
Is the browser you tested on within the compatibility table here?
Assuming it is try this syntax for the native code:
screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;
if (screen.lockOrientationUniversal("portrait-primary")) {
// orientation was locked
} else {
// orientation lock failed
}
I'll check whether we can make our Display orientation calls map to these API's.

Implement File Upload like Dropbox by Appcelerator

I want to implement File Upload function like Dropbox. I use Appcelerator. This function can upload file from Acrobat, iBook, Work, Excel, Drive etc. And make in on iOS.
I have researched on Appcelerator but could not find any solution for this.
I dont know how to access to local storage on iOS or working with another app by Appcelerator.
Can you give me any suggestion about this problem
Thank you very much
You should register CFBundleDocumentTypes in your tiapp.xml ios element, which works the same as modifying the Info.plist in Xcode would for an Obj-C or Swift app. Once you have that completed, you can listen for the resume event in your app, and look at Ti.App.getArguments() to see if your app was launched by choosing "Open In" from another app. You can also look at the folder Inbox inside of Ti.Filesystem.applicationDataDirectory to see if there are any new files in there -- that's where iOS will place them when sharing them to your app.
Your code for handling the document could look like this (in your resume handler):
var cmd = Ti.App.getArguments(),
inboxFiles = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'Inbox').getDirectoryListing() || [];
if (inboxFiles.length > 0) {
inboxFiles = inboxFiles.sort(byLastCreated).map(toTiFile);
if (!cmd.url) {
cmd.url = inboxFiles[0].getNativePath();
}
if (inboxFiles.length > 1) {
for (var i = inboxFiles.length - 1; i >= 1; i--) {
inboxFiles[i].deleteFile();
}
}
}
if (cmd && cmd.url && cmd.url.indexOf('file://') === 0) {
// TODO: Do something interesting with cmd.url.
}

How to detect if browser supports file uploading? (Mobile + Desktop)

I'm developing an application for both mobile and desktop browsers. I'm wondering if there is anyway to detect if a browser supports file uploading. I'm looking specifically for feature detection and not browser detection. Is there any way to find out?
Server-side or client side is fine.
Thanks
client side javascript:
<input type="file" name="file" value="" id="fileUploadField1">
<script type="text/javascript" charset="utf-8">
if (document.getElementById('fileUploadField1').disabled)
{ document.write('your device does not allow uploads'); }
else
{ document.write('your device does allow uploads'); }
</script>
You might be interested to read this article about current input type=file support on mobile and how to detect it: http://viljamis.com/blog/2012/file-upload-support-on-mobile/ (the detection is currently tested to be working on ~120 different mobile browser/mobile OS combinations).
Basically, we are just using similar detection as Modernizr does, but use UA detection as a backup to filter out those mobile browsers that falsely report support (there really doesn’t seem to be any other way to detect it reliably than using these both, feature detection and browser detection).
You can use Modernizr framework with forms-fileinput extension. Give it a try.
if Modernizr.fileinput
// you can use file inputs
Visit the Modernizr download page and check the forms-fileinput extension (expand the "Non-core detects" section).
Modernizr now supports a check for whether or not file uploads are supported.
From: What is the best way to check if user can upload files?
if(Modernizr.fileinput) {
//file input available!
} else {
//No file input :(
}
If you're worried about the size of this library, you can always get one component at a time - http://modernizr.com/download/ ... or you can just copy the code they use: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/forms/fileinput.js
if(navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/)) {
return false;
}
var elem = createElement('input');
elem.type = 'file';
return !elem.disabled;

Mobile detection and supporting older devices

How to identify, when user coming to website with some older phone (not smartphones and iPhones). I'm using jQuery-Mobile with Joomla 1.7.
I use this script:
<script type="text/javascript">// <![CDATA[
var mobile = (/acer|alcatel|audiovox|avantgo|blazer|cdm|digital paths|elaine|epoc|handspring|iemobile|kyocera|lg|midp|mmp|mobile|motorola|nec|o2|openwave|opera mini|operamini|opwv|palm|panasonic|pda|phone|playstation portable|pocket|psp|qci|sagem|sanyo|sec|sendo|sharp|smartphone|symbian|telit|tsm|up-browser|up.browser|up.link|vodafone|wap|windows ce|xiino|ericsson|sonyericsson|iphone|ipod|android|blackberry|samsung|nokia|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
document.location = "http://mysite,com/mobile";
}
// ]]></script>
Site works well with HTC, iPhone, Nokia and so on.
My friend tested with some Ericsson (don't know the model), but site wont work. It shows only PC site, not mobile.
Here are 3 ways to detect mobile...
Community Supported Browser Sniffing through the WURFL project
Custom Browser Sniffing (what you're doing now, quite common though not considered a best practice)
Detecting through feature support.
Option 1: Will probably get you the best overall support if you're really looking to support non-smartphones. This is done on the backend by checking the user agent against a massive database of known devices that is regularly updated by the community. Since it does not rely on JavaScript, it's probably the best way to support absolutely everybody.
Option 2: People on non-smartphones know that surfing web on them sucks. They are therefor less likely to use them for the web. As a percentage of traffic, the percentage of people you will be missing by using detection in JavaScript is probably not worth talking about. For the sites that I have seen, it's been less than 2% on BlackBerry 5 or older and less than 1% for anything else that wasn't Android, iOS, or BlackBerry 6+. I've supported this method of detection before and here is how I did it. Note the allowance for any webkit based option provided the screen is small (isUnknownMobile). This is an attempt at future proofing until such a platform could gain enough traction to be called out.
<script>
var agent = navigator.userAgent;
var isWebkit = (agent.indexOf("AppleWebKit") > 0);
var isIPad = (agent.indexOf("iPad") > 0);
var isIOS = (agent.indexOf("iPhone") > 0 || agent.indexOf("iPod") > 0);
var isAndroid = (agent.indexOf("Android") > 0);
var isNewBlackBerry = (agent.indexOf("AppleWebKit") > 0 && agent.indexOf("BlackBerry") > 0);
var isWebOS = (agent.indexOf("webOS") > 0);
var isWindowsMobile = (agent.indexOf("Windows Phone OS") > 0);
var isSmallScreen = (screen.width < 767 || (isAndroid && screen.width < 1000));
var isUnknownMobile = (isWebkit && isSmallScreen);
var isMobile = (isIOS || isAndroid || isNewBlackBerry || isWebOS || isWindowsMobile || isUnknownMobile);
var isTablet = (isIPad || (isMobile && !isSmallScreen));
function mobileRedirect(mobileView){location.replace((mobileView)?mobileView:"/mobile/index.jsp");}
</script>
Option 3: Feature detection is probably a far more future proofed way of testing if a client is mobile. Consider using the Modernizr Project to see what features are supported. For example, if the device has a small screen and supports canvas, or if it has a touch interface, they're probably mobile. Again, this is front-end based detection and relies on JavaScript.
If you're really looking to redirect EVERYONE who is mobile, the WURFL project is your best bet.
Does the phone support JavaScript?
If not you could use this workaround (if it doesn't affect the UX of your website):
Create a div-container, which is overlaying the whole site
Type in a description (e.g. "This site provides a mobile version") and a link
Hide the div with JavaScript if it not a mobile device or a supported one
This is something i use in my code to check for mobiles
function checkScreen()
{
if (screen.width <= 1000 && screen.height <= 1000)
window.location.replace("MobileURL");
else
window.location.replace("URL");
}
Basically you check the screen res of the client. If it is really low you just redirect to the mobile. you can change the params to be smaller screen if you like.

Resources