Phonegap window.open insert innerHTML - javascript

I like to add innerhtml content(Just Anchor Link) when an external website is opened.
Below code is used to open the external site in inAppBrowser.
var ref = window.open(url, '_blank', 'location=yes');
I tried with below code to add the innerhtml but its not adding the content to the opened website. Can you please suggest an solution?
ref.addEventListener('loadstop', function() {
//Page loaded! some code here..
ref.executeScript({
code: "var evaluateFeedback =
function() {
return 'Done';
};
"},
function(data) {
ref.document.body.innerHTML =
"<b>Hello, stackoverflow! < /
b > ";
}
);
});

ref is a reference to the inAppBrowser object, you can't do ref.document.body.innerHTML because the inAppBrowser object doesn't have a document property
You are using executeScript in the wrong way, the code you want to inject is the code on the code param.
If you do it this way it will work:
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes,toolbarposition=top');
ref.addEventListener('loadstop', function() {
ref.executeScript({code: "document.body.innerHTML = '<b>Hello, stackoverflow!</b>';"});
});
But that will replace your website content with just the Hello, stackoverflow! message, if you want to append it, you should use
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes,toolbarposition=top');
ref.addEventListener('loadstop', function() {
ref.executeScript({code: "document.body.innerHTML = document.body.innerHTML +'<b>Hello, stackoverflow!</b>';"});
});

Related

Opening two instances of InAppBrowser (_system and _blank) prevents events from triggering

We’re currently developing an app with cordova and the InAppBrowser plugin. We're trying to spawn two different IAB instances at the same time. One with the _system browser and another with the _blank option.
The problem we have is that once we open the instance of _system browser, it seems we lose the reference to the previous browser. For this reason, the close event never triggers on the _blank IAB after the _system browser is closed.
This is how the actual code looks like.
// Opening iab main window
var ref = window.open(global.chat_mediador, '_blank','location=no,toolbar=yes');
var handleEvents = function(event) {
// Closing the iab window
if (event.url.match('#close')) {
ref.close();
}
// Trigger custom event
if (event.url.match('#openccard')) {
window.open('https://www.test.example.url.com?customerID=' + event.customerId, '_system', 'location=yes');
}
}
// InAppBrowser events
// This events are duplicated because loadstop works on android and
// loadstart works on ios.
ref.addEventListener('loadstart', handleEvents, false);
ref.addEventListener('loadstop', handleEvents, false);
// Removing the dialog when we close the chat
ref.addEventListener('exit', function(event) {
generali.dialog.close();
}, false);
As you can see we open the first url within the application with the _blank option. Then if in the child application a button is pressed we want to open an instance of a browser in the _system browser.
We’ve tried (without luck) to:
Have a separate reference for the _system browser.
window.open(global.url_ficha + customerId, '_system','location=no');
var cardsRef = window.open(
'https://www.test.example.url.com?customerID=' + customerId,
'_system',
'location=yes'
);
Trigger a custom event outside the reference of the _blank browser
if (event.url.match('openccard')) {
var customerId = event.url.split('openccard-')[1];
var evt = document.createEvent("Event");
evt.initEvent("openccard",true,true);
evt.customerId = customerId;
document.dispatchEvent(evt);
}
Anyone has an idea of what's happening?
It seems that you need to initialize the IAB each time you do a new window.open() if you don't do that the event listeners don't work.
If I use that code it works like a charm.
window.openIAB = function(url, target, options) {
var self = this;
var ref = window.open(url, target, options);
var handleChildEvents = function(ev) {
if (ref != undefined) {
// Closing the iab window
if (ev.url.match('#close')) {
ref.close();
ref = undefined;
}
// Opening card url with system browser
if (ev.url.match('#openccard')) {
var customerId = ev.url.split('#openccard-')[1];
self.ref2 = self.openIAB(
'https://www.test.com?customerID=' + customerId,
'_system',
'location=yes'
);
}
} else {
console.log('InAppBrowser has no reference');
}
};
ref.addEventListener('loadstart', handleChildEvents);
ref.addEventListener('loadstop', handleChildEvents);
ref.addEventListener('loaderror', function(ev) {
console.log('error while loading page');
ref.close();
ref = undefined;
});
ref.addEventListener('exit', function(ev) {
dialog.close();
});
return ref;
};

How to get current link in InnAppBrowser Cordova

Hi i'm working in Xcode v6.1, Cordova v3.7 , jquerymobile v1.4.5
I have a list in which i have urls of external sites. on clicking any site it will open innappbrowser, i want to navigate in innappbrowser page. for instance i am in index page and after clicking or registeration page how can i get the current url from InnAppBrowser. I know the innAppBrowser exit event but couldnt find current url. here the code
function innAppInit(_url) {
try {
app.Log('browser news link=' + _url);
if (_url == null) {
_url = 'http://apache.org';
}
var ref = window.open(encodeURI(_url), '_blank', 'location=no');
console.Dir(ref);
ref.addEventListener('loadstart', function(event) {
$('.ui-loader').hide();
});
ref.addEventListener('exit', function(event) {
alert('exit');
console.Dir(this);
// **how to get current url here;**
});
} catch (e) {
console.log(e);
}
}
You have it in the event of the loadstart, just take it:
var ref = window.open(encodeURI(_url), '_blank', 'location=no');
ref.addEventListener('exit', function()
{
alert(event.url); // here you have the URL
});
See Cordova docs for more info

setTimeout window.open can't take this.href

I'm trying to open the href onMouseOver after 3000ms. But it just popups a blank window. What am I missing?
HTML:
My Rec
JavaScript:
var Popup = null;
function openwindow()
{
var win = window.open()
}
(OK, first off, you need to supply a URL to window.open(), otherwise it doesn't know what page to open to. Aside from that:)
When you do a setTimeout() the value of this is reset in the delayed code.
A quick fix is to extract the URL immediately, and then pass a function into setTimeout() that can use the variable.
<a href="../cc2b/myrec.html"
onMouseOver="var popupUrl = this.href; Popup = setTimeout(function(){openwindow(popupUrl)}), 3000);"
onMouseOut="clearInterval(Popup)">
My Rec
</a>
However, a cleaner solution would be to minimise the code in onMouseOver by setting a timeout in the openhoverpopup function:
<a href="../cc2b/myrec.html"
onMouseOver="openhoverpopup(this.href)"
onMouseOut="clearhoverpopup()">
My Rec
</a>
<script>
var popupTimeout = null;
function openhoverpopup(url) {
popupTimeout = setTimeout(function () {
window.open(url);
}, 3000);
}
function clearhoverpopup() {
clearTimeout(popupTimeout);
}
</script>
You can grab the URL from the element that triggered the mouseover event with either event.target or event.srcElement for older IE browsers.
http://jsfiddle.net/b42pr/1
HTML
Hover
JavaScript
function popURL() {
var url = event.target.href || event.srcElement.href;
console.log("Open URL: " + url);
setTimeout(function(){
window.open(url);
}, 3000)
}
this.href is undefined, I think you're looking for window.location.href:
> this.href
undefined
> window.location.href
"http://stackoverflow.com/questions/18981172/settimeout-window-open-cant-take-this-href"
Also, your function
function openwindow()
{
var win = window.open()
}
Takes no parameters and opens nothing. Change it to
function openwindow(target)
{
var win = window.open(target)
}
Be careful though, most pop-up blockers will block this kind of window.
Try specifying the href outside of the string:
My Rec

Accessing the parent window's content from the child window

I am opening a new window when a button is clicked and then appending the content from this window to the window that has been opened, the jQuery code that I'm using is:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
var wi = $(window);
$(w.document.body).append(wi.find("#datatable_example"));
return false;
});
The problem is, a new window does open but the content from the parent window is not being appended to the newly opened window. I then tried to append wi.find("#datatable_example").html() but that didn't work either.
Can any one please have a look and tell me what I am doing wrong here?
UPDATE
Tried the following from the "duplicate question", but didn't work:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
$(w.document).ready(function () {
$(w.document.body).contents().append($(window).find("#datatable_example"));
});
return false;
});
The problem was, I was using var wi = $(window) instead of var wi = $(window.document). Here is the working code:
$(".printBtn").on("click", function () {
var w = window.open("", "Purchase Report", "width=800, height=1100");
var wi = $(window.document);
$(w.document.body).append(wi.find("#datatable_example"));
return false;
});
The root of your problem is same origin policy that won't let you observe load events for external domains. If you try this in developer console while browsing SO, everything's fine:
var child = window.open( 'http://stackoverflow.com' );
child.onload = function() {
alert( 'Popup loaded!' ); // Fired!
};
However if you try to open a page from other domain, it fails:
var child = window.open( 'http://stackexchange.com' );
child.onload = function() {
// It's not gonna be fired unless you run it from stackexchange.com.
alert( 'Popup loaded!' );
};
The same thing happens when you call window.open() or window.open( '' ) as it tries to load about:blank page which is out of your domain's scope and that's why your browser won't fire attached events (same for child.addEventListener( 'load' )). Also note that the protocol must match as well.
The workaround introduces setTimeout to run the callback in a separate JS thread, hopefully late enough to have DOM ready at that time:
var child = window.open();
setTimeout( function() {
var doc = child.document,
p = doc.createElement( 'p' );
p.innerHTML = 'Hello world!';
doc.body.appendChild( p );
} );
It works for me in latest Chrome, however different browsers sometimes do strange thing in such edge cases so you may need to tune this code with greater delay, sequential check or something else if it fails in your case.
So go ahead and tell us if it worked for you as I'm curious whether such workaround is fine for production code ;)

Javascript Function Removal and Replacement

My site is AJAX based so I have an window.onbeforeunload = function(){};. However, I have mailto link and when I click those mailto links, the confirm reload pops up, which I don't like. Is there a way to write a function to remove the window.onbeforeunload = function(){};, pull up the mail editor from the mailto link, and then put the window.onbeforeunload = function(){}; back?
Thanks
You could add a script like this after your anchor:
Mail
<script>
(function(w, d){
var anchors = d.getElementsByTagName('a');
var a = anchors[anchors.length - 1];
a.onclick = function(){
var old_unload = w.onbeforeunload;
w.onbeforeunload = null;
w.location = a.href;
setTimeout(function(){
w.onbeforeunload = old_unload;
}, 0);
return false;
};
})(window, document);
</script>
JSFiddle Demo
Note: The first revision did not work, because w.onbeforeunload = old_unload was running before the browser changed to the mailto page. Using setTimeout to make the assignment asynchronous solves that problem.

Categories

Resources