Reputation: 524
I have this code in a click event
let browser = new InAppBrowser('http://example.com/test', '_self');
browser.executeScript({code: "(function() { alert(123); })()"});
When i click the button, inAppBrowser opens the page, but the script doesn't run.
I closed the browser and then clicked the button again, now the script does run.
Why it's not running for the first time?
Upvotes: 5
Views: 17438
Reputation: 141
On recent development, I have noticed that no event listener is working on the latest ionic project. However, without adding any event listener you can add javascript inside your InAppBrowser by directly calling InAppBrowser.executeScript() function.
Upvotes: 0
Reputation: 1
@RezaT1994 Changing '_self' to '_blank' fixed this problem for me.
let browser = new InAppBrowser('http://example.com/test', '_blank');
browser.executeScript({code: "(function() { alert(123); })()"});
Upvotes: 0
Reputation: 1177
@Andrews' answer worked perfectly for me. Here is my full code for an Ionic 3 app using @ionic-native/themeable-browser:
let options: ThemeableBrowserOptions = {
statusbar: { color: '#1976d2ff' },
toolbar: { height: 44, color: '#1976d2ff' },
closeButton: { align: 'right', event: 'closed', wwwImage: '/assets/images/icons/close-empty.png', wwwImagePressed: '/assets/images/icons/close-outline.png', wwwImageDensity: 3 },
usewkwebview: 'yes',
disallowoverscroll: 'yes',
allowInlineMediaPlayback: 'yes',
mediaPlaybackRequiresUserAction: 'no'
},
browser: ThemeableBrowserObject = self.iab.create(url, '_blank', options);
if (this.platform.is('ios')) {
browser.on('loadstop').subscribe(() => {
browser.executeScript({ code: 'document.body.classList.add("cordova-ios");' });
});
}
This way I can style iOS in Cordova explicitly via body.cordova-ios
class inheritance
Upvotes: 0
Reputation: 13
Try running the following code. This was working for me.
var ref = cordova.InAppBrowser.open("https://www.test.com/", '_blank');
ref.addEventListener('loadstart', function() {
ref.executeScript({
code: '//put the script you want to run here'
});
})
Please make sure that _blank is given and not _system. _system will open the native browser (eg chrome)
Upvotes: 0
Reputation: 186
It's not working in this way anymore. Try it!
browser.on('loadstop').subscribe(() => {
browser.executeScript({code: 'your_code'})
});
This is working for me.
Upvotes: 5
Reputation: 8712
Add executeScript inside a InAppBrowser.addEventListener (loadstart, loadstop, loaderror) then it will run at the first time. I am using ionic 1 but I guess it will also work in ionic 2. I added a sample code below. (This is how it look like in ionic 1).
browser.addEventListener('loadstart', function(){
browser.executeScript({code: "(function() { alert(123); })()"});
})
Upvotes: 10