I wonder if this is possible to execute JavaScript inside phonegap childbrowser window so we can manipulate websites under phonegap app?
Looking at the big picture as one can create a function in Objective-C which executes that JS into childbrowser (modifying childbrowser.m and childbrowser.h files) and creating JS wrapper of it so one can call JS function to execute JS inside childbrowser.
I want you to modify ChildBrowser for me to have that functionality so I shouldn't lost doing it. At least give me initial steps.
Alright I just tried and it worked in a single go. That was amazing! I just modified ChildBrowser plugin of PhoneGap and it worked.
UPDATED
I finally got few minutes to update the answer for those who will encounter the same issue.
ChildBrowserCommand.h
- (void) jsExec:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
ChildBrowserCommand.m
- (void) jsExec:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; {
[childBrowser executeJS:(NSString *)[arguments objectAtIndex:0]];
}
ChildBrowserViewController.h
- (void)executeJS:(NSString *)js;
ChildBrowserViewController.m
- (void) executeJS:(NSString *)js {
[webView stringByEvaluatingJavaScriptFromString:js];
}
ChildBrowser.js
/* MIT licensed */
// (c) 2010 Jesse MacFadyen, Nitobi
function ChildBrowser()
{
}
// Callback when the location of the page changes
// called from native
ChildBrowser._onLocationChange = function(newLoc)
{
window.plugins.childBrowser.onLocationChange(newLoc);
}
// Callback when the user chooses the 'Done' button
// called from native
ChildBrowser._onClose = function()
{
window.plugins.childBrowser.onClose();
}
// Callback when the user chooses the 'open in Safari' button
// called from native
ChildBrowser._onOpenExternal = function()
{
window.plugins.childBrowser.onOpenExternal();
}
// Pages loaded into the ChildBrowser can execute callback scripts, so be careful to
// check location, and make sure it is a location you trust.
// Warning ... don't exec arbitrary code, it's risky and could cause your app to fail.
// called from native
ChildBrowser._onJSCallback = function(js, loc)
{
// Not Implemented
window.plugins.childBrowser.onJSCallback(js, loc);
}
/* The interface that you will use to access functionality */
// Show a webpage, will result in a callback to onLocationChange
ChildBrowser.prototype.showWebPage = function(loc)
{
PhoneGap.exec("ChildBrowserCommand.showWebPage",loc);
}
// close the browser, will NOT result in close callback
ChildBrowser.prototype.close = function()
{
PhoneGap.exec("ChildBrowserCommand.close");
}
// Not Implemented
ChildBrowser.prototype.jsExec = function(jsString)
{
// Not Implemented!!
PhoneGap.exec("ChildBrowserCommand.jsExec", jsString);
}
// Note: this plugin does NOT install itself, call this method some time after deviceready to install it
// it will be returned, and also available globally from window.plugins.childBrowser
ChildBrowser.install = function()
{
if(!window.plugins)
{
window.plugins = {};
}
window.plugins.childBrowser = new ChildBrowser();
return window.plugins.childBrowser;
}
My global variable.
var CB = null;
On my DeviceReady event.
CB = ChildBrowser.install();
if (CB != null) {
CB.onLocationChange = onCBLocationChanged;
}
I can execute any JS into webpage using.
CB.jsExec("alert('I am from ChildBrowser!');");
I hope my contribution to this will bring smile on your face.
Related
I am investigating using Ionic 4/ Capacitor to target Windows via the Electron option, for an application where I want to use SQLite.
Using the Ionic Native SQLite plugin, which wraps this Cordova plugin, out of the box, as far as I can see, the Windows support is for UWP, and not Desktop, which runs using Electron in Ionic Capacitor wrapper.
My plan, was to see if I could use Electron SQLite package, and then call this from my Ionic application by making a wrapper class for the Ionic native similar to what I used to get browser support by following this tutoral
If I can call the Electron code from my Ionic app, then I can't see why this wouldn't work.
So, my question here is, can I call code (I will add functions to use the SQlite) I add to the hosting Electron application from within the Ionic (web) code? And if so, how?
Thanks in advance for any help
[UPDATE1]
Tried the following...
From an Ionic page, I have a button click handler where I raise an event..
export class HomePage {
public devtools() : void {
let emit = new EventEmitter(true);
emit.emit('myEvent');
var evt = new CustomEvent('myEvent');
window.dispatchEvent(evt);
}
Then within the Electron projects index.js, I tried..
mainWindow.webContents.on('myEvent', () => {
mainWindow.openDevTools();
});
const ipc = require('electron').ipcMain
ipc.on('myEvent', (ev, arg) => {
mainWindow.openDevTools();
});
But neither worked.
I should mention I know very little about Electron. This is my first exposure to it (via Capacitor)
In case someone is interested, this is how I solved this.
Im am using Ionic 4 / Capacitor + Vue 3.
In my entry file (app.ts) I have declared a global interface called Window as follows:
// app.ts
declare global { interface Window { require: any; } }
Then, I have written the following class:
// electron.ts
import { isPlatform } from '#ionic/core';
export class Electron
{
public static isElectron = isPlatform(window, 'electron');
public static getElectron()
{
if (this.isElectron)
{
return window.require('electron');
}
else
{
return null;
}
}
public static getIpcRenderer()
{
if (this.isElectron)
{
return window.require('electron').ipcRenderer;
}
else
{
return null;
}
}
public static getOs()
{
if (this.isElectron)
{
return window.require('os');
}
else
{
return null;
}
}
}
And I use it like this:
//electronabout.ts
import { IAbout } from './iabout';
import { Plugins } from '#capacitor/core';
import { Electron } from '../utils/electron';
export class ElectronAbout implements IAbout
{
constructor() { }
public async getDeviceInfo()
{
let os = Electron.getOs();
let devInfo =
{
arch: os.arch(),
platform: os.platform(),
type: os.type(),
userInfo: os.userInfo()
};
return devInfo;
}
public async showDeviceInfo()
{
const devInfo = await this.getDeviceInfo();
await Plugins.Modals.alert({ title: 'Info from Electron', message: JSON.stringify(devInfo) });
}
}
This is working but, of course, I still need to refactor the Electron class (electron.ts). Probably using the singleton pattern is a better idea.
I hope this helps.
Update
You can communicate from the render process with your main process (index.js) like this:
//somefile.ts
if (Electron.isElectron)
{
let ipc = Electron.getIpcRenderer();
ipc.once('hide-menu-button', (event) => { this.isMenuButtonVisible = false; });
}
//index.js
let newWindow = new BrowserWindow(windowOptions);
newWindow.loadURL(`file://${__dirname}/app/index.html`);
newWindow.webContents.on('dom-ready', () => {
newWindow.webContents.send('hide-menu-button');
newWindow.show();
});
I dug into this yesterday and have an example for you using angular(this should apply to ionic too).
in your service declare require so we can use it
//Below your imports
declare function require(name:string);
Then in whatever function you want to use it in:
// Require the ipcRenderer so we can emit to the ipc to call a function
// Use ts-ignore or else angular wont compile
// #ts-ignore
const ipc = window.require('electron').ipcRenderer;
// Send a message to the ipc
// #ts-ignore
ipc.send('test', 'google');
Then in the created index.js within the electron folder
// Listening for the emitted event
ipc.addListener('test', (ev, arg) => {
// console.log('ev', ev);
console.log('arg', arg);
});
Its probably not the correct way to access it but its the best way i could find. From my understanding the ipcRenderer is used for when you have multiple browsers talking to each other within electron. so in our situation it enables our web layer to communicate with the electron stuff
I am running with multiCapabilities, and would like to know if it is possible to know what capability is currently used, both in the onPrepare function and/or the testcase itself.
The use case is that I am planning to run my tests both on chrome and on android. For Chrome the window should be resized to required dimensions, however running the same code on selendroid gives an exception because the method is not implemented (also resizing a window on a device does not really make sense):
So, the idea was to somehow wrap the offending code in a simple check like so:
if(browser != 'android')
browser.driver.manage().window().setSize(480, 800);
There are also other use cases, but that's the most important one for now.
I do stuff like that within the onPrepare section, e.g.
// Return if current browser is IE, optionally specifying if it is a particular IE version
browser.isInternetExplorer = function(ver) {
var browserName, version, ie;
return browser.getCapabilities().then(function(s) {
browserName = s.caps_.browserName;
version = s.caps_.version;
ie = /i.*explore/.test(browserName);
if (ver == null) {
return ie;
} else {
return ie && ver.toString() === version;
}
});
};
Then, later on, i use it like this:
if (browser.isInternetExplorer()) {...}
For android this should work:
browser.isAndroid = function(ver) {
var browserName, version;
return browser.getCapabilities().then(function(s) {
browserName = s.caps_.browserName;
version = s.caps_.version;
return /droid/.test(browserName);
});
};
A Webview will display links in the content HTML as having blue underlines. So if you have something in the HTML like
blah blah
... it is clearly visible as a link.
The Webview also allows you to click on phone numbers and addresses (even if those are just text in the HTML, not links) to launch the Dialer or Maps.
How can one get Webview to display those (Linkify, probably) links with underlines etc? It's easy enough in a TextView since one can get the spans from a TextView and style them, but Webview doesn't expose any way to retrieve that data... at least not that I can see looking through the docs.
Here is some JS code which can be injected to linkify phone numbers, emails and urls:
function linkify() {
linkifyTexts(linkifyPhoneNumbers);
linkifyTexts(linkifyEmails);
linkifyTexts(linkifyWebAddresses1);
linkifyTexts(linkifyWebAddresses2);
}
function linkifyPhoneNumbers(text) {
text = text.replace(/\b\+?[0-9\-]+\*?\b/g, '$&');
return text;
}
function linkifyEmails(text) {
text = text.replace(/(\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim, '$1');
return text;
}
function linkifyWebAddresses1(text) {
text = text.replace(/(\b(https?|ftp):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim, '$1');
return text;
}
function linkifyWebAddresses2(text) {
text = text.replace(/(^|[^\/])(www\.[\S]+(\b|$))/gim, '$1$2');
return text;
}
var linkifyTexts = function(replaceFunc)
{
var tNodes = [];
getTextNodes(document.body,false,tNodes,false);
var l = tNodes.length;
while(l--)
{
wrapNode(tNodes[l], replaceFunc);
}
}
function getTextNodes(node, includeWhitespaceNodes,textNodes,match) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !/^\s*$/.test(node.nodeValue)) {
if(match){
if(match.test(node.nodeValue))
textNodes.push(node);
}
else {
textNodes.push(node);
}
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
var subnode = node.childNodes[i];
if (subnode.nodeName != "A") {
getTextNodes(subnode,includeWhitespaceNodes,textNodes,match);
}
}
}
}
function wrapNode(n, replaceFunc) {
var temp = document.createElement('div');
if(n.data)
temp.innerHTML = replaceFunc(n.data);
else{
//whatever
}
while (temp.firstChild) {
n.parentNode.insertBefore(temp.firstChild,n);
}
n.parentNode.removeChild(n);
}
Given this:
http://code.google.com/p/android/issues/detail?id=742
it still doesn't seem to be a way to do this from Java directly. One thing that might work is to write some JavaScript code and run it after page is loaded, e.g. as given here:
In Android Webview, am I able to modify a webpage's DOM?
Here's an example of a similar thing:
Disabling links in android WebView
where the idea is to disable links. You may be able to use a similar approach to add some CSS, including underlining. A couple of other SOqs / links that might help:
Android: Injecting Javascript into a Webview outside the onPageFinished Event
Android: Injecting Javascript into a Webview outside the onPageFinished Event
http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview
Injecting Javascript into a Webview outside the onPageFinished Event (Using DatePicker to set a date on an input of a WebView)
Hope this helps.
I have this struct:
Example.Form = Ext.extend(Ext.form.FormPanel, {
// other element
, onSuccess:function(form, action) {
}
}
Ext.reg('exampleform', Example.Form);
Ext.onReady(function() {
var win = new Ext.Window({
id:'formloadsubmit-win'
,items:{id:'add', xtype:'exampleform'}
});
win.show();
})
I delete extra code above...
I want to do this: when I submit form on function-> onSuccess in Example.Form class able to close window on body. (When success results were submited and than the body of the window that opens become closed)
I apologize for my bad English.
The structure of the code should allow a place to store the components you are registering as xtypes. It should also have a top level namespace for the components that make up the app. This way you can always reference the parts of your app. It is also a good idea to break out the controller logic. For a small app, a single controller may work fine but once the app grows it is good to have many controllers for the app, one for each piece.
Here is a modified version of the code you put in that example. It will handle the success event and is structured to fit the recommendations noted above.
Ext.ns('Example');
/* store components to be used by app */
Ext.ns('Example.lib');
/* store instances of app components */
Ext.ns('Example.app');
Example.lib.Form = Ext.extend(Ext.form.FormPanel, {
// other element
// moved to app controller
//onSuccess:function(form, action) {
//}
});
Ext.reg('exampleform', Example.lib.Form);
Example.lib.FormWindow = Ext.extend(Ext.Window,{
initComponent: function(){
/* add the items */
this.items ={itemId:'add', xtype:'exampleform'};
/* ext js requires this call for the framework to work */
Example.lib.FormWindow.superclass.initComponent.apply(this, arguments);
}
});
Ext.reg('exampleformwin', Example.lib.FormWindow);
/*
manage/control the app
*/
Example.app.appController = {
initApp: function(){
Example.app.FormWindow = Ext.create({xtype:'exampleformwin', id:'formloadsubmit-win'});
Example.app.FormWindow.show();
/* get a reference to the 'add' form based on that item id and bind to the event */
Example.app.FormWindow.get('add').on('success', this.onAddFormSuccess, this );
},
/* the logic to handle the add-form's sucess event */
onAddFormSuccess: function(){
Example.app.FormWindow.hide();
}
}
Ext.onReady(function() {
/* start the app */
Example.app.appController.initApp()
})
Im trying to pass multiple things from a webpage inside a UIWebView back to my iPhone app via the shouldStartLoadWithRequest method of the UIWebView.
Basically my webpage calls window.location.href = "command://foo=bar" and i am able to intercept that in my app no problem. Now if i create a loop and do multiple window.location.href calls at once, then shouldStartLoadWithRequest only appears to get called on once and the call it gets is the very last firing of window.location.href at the end of the loop.
The same thing happens with the webview for Android, only the last window.location.href gets processed.
iFrame = document.createElement("IFRAME");
iFrame.setAttribute("src", "command://foo=bar");
document.body.appendChild(iFrame);
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
So this creates an iframe, sets its source to a command im trying to pass to the app, then as soon as its appended to the body shouldStartLoadWithRequest gets called, then we remove the iframe from the body, and set it to null to free up the memory.
I also tested this on an Android webview using shouldOverrideUrlLoading and it also worked properly!
I struck this problem also and here is my solution that works for me.
All my JavaScript functions use this function __js2oc(msg) to pass data
and events to Objective-C via shouldStartLoadWithRequest:
P.S. replace "command:" with your "appname:" trigger you use.
/* iPhone JS2Objective-C bridge interface */
var __js2oc_wait = 300; // min delay between calls in milliseconds
var __prev_t = 0;
function __js2oc(m) {
// It's a VERY NARROW Bridge so traffic must be throttled
var __now = new Date();
var __curr_t = __now.getTime();
var __diff_t = __curr_t - __prev_t;
if (__diff_t > __js2oc_wait) {
__prev_t = __curr_t;
window.location.href = "command:" + m;
} else {
__prev_t = __curr_t + __js2oc_wait - __diff_t;
setTimeout( function() {
window.location.href = "command:" + m;
}, (__js2oc_wait - __diff_t));
}
}
No, iframe's url changing won't trigger shouldOverrideUrlLoading, at least no in Android 2.2.