Before Firefox Quantum, I can detect firefox android in firefox addon with this snippet below.
const { Cc, Ci } = require('chrome');
/**
* Is firefox android?
*
* #returns {boolean} true if there is firefox android in firefox addon
* #see https://developer.mozilla.org/en-US/Add-ons/Firefox_for_Android/Code_snippets#Supporting_both_desktop_and_mobile
*/
module.exports = () =>
Cc['#mozilla.org/xre/app-info;1']
.getService(Ci.nsIXULRuntime)
.widgetToolkit.toLowerCase() === 'android';
But now, this snippet is archived. How to detect this?
Cc, Ci and require-syntax is XUL/SDK technology which has been deprecated in favour of WebExtensions.
In a WebExtension, you can retrieve platform info using browser.runtime.getPlatformInfo:
browser.runtime.getPlatformInfo().then((info) => {
console.log(info.os); // will return android
});
This resolves into a PlatformInfo object, which contains the "os" property where "android" will be set. https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/PlatformOs
For more details, see
https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/getPlatformInfo
Related
I just created an electron app which is powered by Flask.
It works nicely when I run the app in powershell, but when I build this app with electron-packager, It succeeds, but the app does not work.
It seems python code would not be included in the app.
How can I build the app with integrating all python code and modules I am using in the app?
I am using any python modules like pandas
I was able to package an electron-flask app using guidelines from here which gives better details of the answer given below.
First make sure that the pyinstaller .exe actually starts the server correctly when you run it and that when you direct to the hosted page in your browser that the app does everything you need it to do. Packaging flask app tutorial is here.
And then make sure when you are executing:
var subpy = require('child_process').spawn('./dist/hello/hello');
That you make sure its:
var subpy = require('child_process').spawn('path_to_flask_exe');
Build the flask app with PyInstaller.. You can find various tutorial on it through google.. Pick one that suits your needs. Always good to read the official documentation https://www.pyinstaller.org/ .
Well I don't know your approach of creating the electron entry point. what i did was, on the entry point (usually main.js for me) I have created a function which is called on app is ready. Some of the stuffs i got from Python on Electron framework and from https://github.com/fyears/electron-python-example
main.js
'use strict';
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const path = require('path');
// This method will be called when Electron has finished
// initialization and is ready to create browser mainWindow.
// Some APIs can only be used after this event occurs.
var mainWindow = null;
function createWindow(){
// spawn server and call the child process
var rq = require('request-promise');
mainAddr = 'http://localhost:4040/'
// tricks 1 worked for me on dev.. but building installer of electron
// server never started.. didn't find time to fixed that
// var child = require('child_process').spawn('python',
// ['.path/to/hello.py']);
// or bundled py
// var child = require('child_process').spawn('.path/to/hello.exe');
// tricks 2, a little variation then spawn :)
var executablePath = './relative/path/to/your/bundled_py.exe';
var child = require('child_process').execFile;
child(executablePath, function(err, data) {
if(err){
console.error(err);
return;
}
console.log(data.toString());
});
// Create the browser mainWindow
mainWindow = new BrowserWindow({
minWidth: 600,
minHeight: 550,
show: false
});
// Load the index page of the flask in local server
mainWindow.loadURL(mainAddr);
// ready the window with load url and show
mainWindow.once('ready-to-show', () => {
mainWindow.show();
});
// Quit app when close
mainWindow.on('closed', function(){
mainWindow = null;
// kill the server on exit
child.kill('SIGINT');
});
// (some more stuff, eg. dev tools) skipped...
};
var startUp = function(){
rq(mainAddr)
.then(function(htmlString){
console.log('server started!');
createWindow();
})
.catch(function(err){
//console.log('waiting for the server start...');
startUp();
});
};
app.on('ready', startUp)
app.on('quit', function() {
// kill the python on exit
child.kill('SIGINT');
});
app.on('window-all-closed', () => {
// quit app if windows are closed
if (process.platform !== 'darwin'){
app.quit();
}
});
I want to simulate a mobile device in desktop environment. I can't find a argument to transform mouse event to touch event.
How can I approach this job? Any hint will be great. Thank you so much.
I think I figured it out. Dev environment:
node 7.4.0
Chromium 54.0.2840.101
Electron 1.5.1
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
frame: false,
x: -1920,
y: 0,
autoHideMenuBar: true,
icon: 'assets/icons/win/app-win-icon.ico'
});
try {
// works with 1.1 too
mainWindow.webContents.debugger.attach('1.2')
} catch (err) {
console.log('Debugger attach failed: ', err)
}
const isDebuggerAttached = mainWindow.webContents.debugger.isAttached()
console.log('debugger attached? ', isDebuggerAttached)
mainWindow.webContents.debugger.on('detach', (event, reason) => {
console.log('Debugger detached due to: ', reason)
});
// This is where the magic happens!
mainWindow.webContents.debugger.sendCommand('Emulation.setTouchEmulationEnabled', {
enabled: true,
configuration: 'mobile',
});
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true,
show: false,
backgroundColor: '#8e24aa ',
}));
// Show the mainwindow when it is loaded and ready to show
mainWindow.once('ready-to-show', () => {
mainWindow.show()
})
}
// Listen for app to be ready
app.on('ready', createWindow);
Take a look at this Electron github issue or this Atom Discussion for ideas on how to get the touch working with Electron.
As far as how to approach it, I would look through the mouse events and touch events and just wire up a function that combines the Electron api and the relevant web api for mouse/touch.
Looking at the web-contents API, the only thing you can do is to open the dev tools with:
// win being a BrowserWindow object
win.webContents.openDevTools();
Then you will have to manually click on the responsive tools (the smartphone icon), and you will get into the mode you want.
But I am afraid there is no way to do it programatically. Mostly because it is considered as a development tool, and not a browser feature, so you will have the toolbar at the top and all these things. Not really something you want on Production.
You can try to use Microsoft Windows Simulator. You need to install Visual Studio 2019 with Universal Windows Platform development then run the simulator through:
C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Simulator\16.0\Microsoft.Windows.Simulator.exe
I tested my electron app that also needs to run well both on touchscreen devices and devices without touch screen using this and it works really well to simulate touchscreen devices.
Do not forget to switch to touchscreen input on the right side of the panel, otherwise, the default input will simulate a mouse pointer.
For an ionic 2 app to print using Sunmi V1, added native plugin for printer by executing
cordova plugin add cordova-plugin-printer
First I checked whether the printer is available by
checkPrinter() {
this.printer.check().then(function () {
alert("Printer available");
}, function () {
alert("Printer not available");
});
}
It alerts "Printer available"
But the below method doesn't prompt any message
printData() {
this.printer.isAvailable().then(function () {
this.printer.print("Test Data").then(function () {
alert("Printed");
}, function () {
alert("Printing error");
});
}, function () {
alert('Unavailable');
});
}
So I called Printer.print method directly as below
printData(){
this.printer.print("Test Data").then(function () {
alert("Printed");
}, function () {
alert("Printing Error");
});
}
This method opens Print dialog to choose printer
If I select 'All Printers' from the dropdown to select printer instead of 'Save as PDF', then the search screen appears and keeps on searching...
Is some configuration missing or is it possible to interact with POS printers using cordova printer plugin?
Thanks.
i found a new plugin created by labibramadhan. Thanks labib
you can find the plugin here
https://github.com/labibramadhan/cordova-sunmi-inner-printer
First, install by typing ionic
cordova plugin add https://github.com/labibramadhan/cordova-sunmi-inner-printer.git
Then, use it on your cordova javascript codes by calling:
window.sunmiInnerPrinter.printOriginalText("Hello World!")
window.sunmiInnerPrinter.[methods available on here]
https://github.com/labibramadhan/cordova-sunmi-inner-printer/blob/master/www/innerprinter.js
Thank you
"Sunmi printer itself is not a network printer, web applications can not communicate directly with the printer, you need to accept data on the android applications" - From the documents available in their site. (I also contacted their support team but there was no proper reply)
As of now it doesn't support, so I am using github.com/shangmisunmi/SunmiPrinterDemo as example and developing the application in Android instead of ionic 2.
According to the documentation is not that easy:
http://docs.sunmi.com/htmls/index.html?lang=en##V1%20Docs%20&%20Resources
This is a weird issue, that is some what hard to generate and explore.
While building a web-app using Angular, my boss found that all the buttons on the app that are using ng-click directive are not working.
Now, this issue only happens on iphone 6 with IOS 8.3 and using the safari browser.
I can say that when was tested on iPhone5 (All versions), iPhone 6 (IOS 9), Safari for windows and all other browsers (Mobile and desktop), ng-click works like a charm.
The app is being build using Angular 1.4.3.
This is the code for the button, as you can see, nothing special about it:
<button class="btn calculate-button" ng-click="onCalculate()">Calculate</button>
And in the controller:
$scope.onCalculate = function () {
//Do something... And then:
$state.go('someplace');
};
I tried many changes that were suggested here, including ng-touch, ng-bind, building my own click directive as follows:
.directive('basicClick', function($parse, $rootScope) {
return {
compile: function(elem, attr) {
var fn = $parse(attr.basicClick);
return function(scope, elem) {
elem.on('click', function(e) {
fn(scope, {$event: e});
scope.$apply();
});
};
}
};
});
Couldn't find any proper solution for the problem.
Thanks.
IOS 8.4.1 Update has a known issue which stop ng-link and ng-click to work.
Using "touchstart click" can possibly solve this issue.
app.directive("ngMobileClick", [function () {
return function (scope, elem, attrs) {
elem.bind("touchstart click", function (e) {
e.preventDefault();
e.stopPropagation();
scope.$apply(attrs["ngMobileClick"]);
});
}
}])
HTML call: ng-mobile-click="onCalculate()"
I fixed it in the end.
The problem was in the //Do something... And then: part of the function.
At some point along the way, that function saves some data to the browser local storage.
My boss was using private browsing on safari, and apparently when using private browsing on safari, the browser wont save and data on the local storage and it throws an exception and kills the code.
Well, thanks any way.
How can I log data or messages to the console in my Electron app?
This really basic hello world opens the dev tools by default, by I am unable to use console.log('hi'). Is there an alternative for Electron?
main.js
var app = require('app');
var BrowserWindow = require('browser-window');
require('crash-reporter').start();
var mainWindow = null;
app.on('window-all-closed', function() {
// Mac OS X - close is done explicitly with Cmd + Q, not just closing windows
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function(){
mainWindow = new BrowserWindow({ width: 800, height: 600});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.openDevTools();
mainWindow.on('closed', function(){
mainWindow = null;
});
});
console.log works, but where it logs to depends on whether you call it from the main process or the renderer process.
If you call it from the renderer process (i.e. JavaScript that is included from your index.html file) it will be logged to the dev tools window.
If you call it from the main process (i.e. in main.js) it will work the same way as it does in Node - it will log to the terminal window. If you're starting your Electron process from the Terminal using electron . you can see your console.log calls from the main process there.
You can also add an environment variable in windows:
ELECTRON_ENABLE_LOGGING=1
This will output console messages to your terminal.
There is another way of logging to the console from inside the renderer process. Given this is Electron, you can access Node's native modules. This includes the console module.
var nodeConsole = require('console');
var myConsole = new nodeConsole.Console(process.stdout, process.stderr);
myConsole.log('Hello World!');
When this code is run from inside the renderer process, you will get Hello World! in the terminal you ran Electron from.
See https://nodejs.org/api/console.html for further documentation on the console module.
Yet another possibility is accessing the main process console using remote.getGlobal(name):
const con = require('electron').remote.getGlobal('console')
con.log('This will be output to the main process console.')
Adding to M. Damian's answer, here's how I set it up so I could access the main process's console from any renderer.
In your main app, add:
const electron = require('electron');
const app = electron.app;
const console = require('console');
...
app.console = new console.Console(process.stdout, process.stderr);
In any renderer, you can add:
const remote = require('electron').remote;
const app = remote.app;
...
app.console.log('This will output to the main process console.');
process.stdout.write('your output to command prompt console or node js ')
You can use the npm package electron-log https://www.npmjs.com/package/electron-log
It will log your error, warn, info, verbose, debug, silly outputs in your native os log.
var log = require('electron-log');
log.info('Hello, log');
log.error('Damn it, an error');
Sorry to raise an old thread but this is the top result for "how to output console.log to terminal" (or similar searches.
For anyone looking to gain a bit more control over what is output to the terminal you can use webContents.on('console-message') like so:
mainWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
console.log(message + " " +sourceId+" ("+line+")");
});
See:
webContents Documentation
webContents entry on BrowserWindow docs
This is a follow up to cscsandy5's answer for some addition information, info from here
process.stdout.write('your output to command prompt console or node js ')
This code works great for just outputting a simple debug message to the terminal window you launched the electron app from and is is what console.log is build on top of.
Here is an example snippet (based on tutorialspoint electon tutorial) of a jQuery script that will write hello to the terminal every time the button is pressed (warning: you need to add your own line breaks in the output strings!)
let $ = require('jquery')
var clicks = 0;
$(function() {
$('#countbtn').click(function() {
//output hello <<<<<<<<<<<<<<<<<<<<<<<
process.stdout.write('hello')
$('#click-counter').text(++clicks);
});
$('#click-counter').text(clicks);
});
This is what I use:
let mainWindow // main window reference, you should assign it below 'mainWindow = new BrowserWindow'
function log(...data) {
mainWindow.webContents.executeJavaScript("console.log('%cFROM MAIN', 'color: #800', '" + data + "');");
}
Example use (same as console.log):
log('Error', { msg: 'a common log message' })
log('hello')
Source: https://github.com/fuse-box/fuse-box-electron-seed/tree/master/src/main in the logger.js file, here you can see a real use case.
After some investigation, here my understanding:
Code
(1) main.js
const createPyProc = () => {
console.log('In createPyProc')
...
console.log('scriptStart=%s', scriptStart)
...
console.log('scriptOther=%s', scriptOther)
...
}
...
let mainWindow = null
const createWindow = () => {
mainWindow = new BrowserWindow(
{
width: 1024,
height: 768,
webPreferences: {
nodeIntegration: true,
}
}
)
mainWindow.loadURL(require('url').format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.webContents.openDevTools()
mainWindow.on('closed', () => {
mainWindow = null
})
}
...
Note: which use openDevTools to opened Electron Dev Tools
(2) render.js
const zerorpc = require("zerorpc")
...
console.log("clientStart %d server is ready", PORT_START)
...
})
(3) render.js is called by: index.html
<!DOCTYPE html>
<html>
...
<script>
require('./renderer.js')
</script>
</html>
console.log
Output Logic
two process and its console.log output:
main process = NodeJS process = here Electron UI process
-> console.log in main.js will output log to here
render process
-> console.log in render.js will output log to here
Screenshot Example
DEBUG=Development mode
run ./node_modules/.bin/electron .
Production=Release mode = the xxx.app pacakged by eletron-builder
run /path_to_your_packaged_mac_app/xxx.app/Contents/MacOS/yourBinaryExecutable
added export ELECTRON_ENABLE_LOGGING=true, render.js console.log ALSO output to main process terminal
console.log() will work fine for debugging. As the electron is built on top of browser, it has DevTools support you can use devtools for debugging purpose. However, there is a hysterical behaviour of console.log() method. When you call the console.log() from main process of electron app, it will output to the terminal window from where you just launched the app and when you call it from renderer process it will output to the DevTools console.
Everything Alex Warren wrote is true. Important here is how Electron is started. If you use the standard script in the package.json file it will not work. To make console.log() work replace the old script with this new one.
Old one:
"scripts": {
"start": "electron ."
}
New one:
"scripts": {
"start": ".\\node_modules\\electron\\dist\\electron.exe ."
}
Now all console.log() calls are displayed in the terminal as well.
With this You can use developer tools of main Browser window to see logs
function logEverywhere(s) {
if (_debug === true) {
console.log(s);
// mainWindow is main browser window of your app
if (mainWindow && mainWindow.webContents) {
mainWindow.webContents.executeJavaScript(`console.log("${s}")`);
}
}
}
Example logEverywhere('test')
will output // test in console panel of main browser window's developer tools
You may need enhance this method to accept multiple args (You can done it with spread operator by es6)
Well, this is 2019 and I cant believe no one mentioned this trick in all the answers above.
Ok, so, how about logging directly to the browser console directly from the main?
I provided my answer here: https://stackoverflow.com/a/58913251/8764808
Take a look.
A project I'm working on was using electron-react-boilerplate. That has electron-devtools-installer#2.4.4, which somehow via cross-unzip causes a process to crash with Error: Exited with code 9 .
Upgrading to electron-devtools-installer#3.1.1, as proposed in electron-react-boilerplate#v2.0.0 resolved it so my console.log, console.error, etc statements worked as expected.
for log purpose, i would recommend you to use the electron-log package