Cef Sharp not showing popup window called using window.open - javascript

I've build an application using CefSharp.WinForms. All is good but when any website uses to show a popup using javascript window.open() it won't work.
I've implemented ILifeSpanHandler it working very fine for the links but fails when used window.open(). Can any one help me how to handle window.open().
EDIT-1 LifeSpanHandler Implementation
public class LifeSpanHandler : ILifeSpanHandler
{
public bool DoClose(IWebBrowser browserControl, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
{
//throw new NotImplementedException();
}
public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
{
//throw new NotImplementedException();
}
public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IWindowInfo windowInfo, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
ChromiumWebBrowser chromiumBrowser = null;
var windowX = windowInfo.X;
var windowY = windowInfo.Y;
var windowWidth = (windowInfo.Width == int.MinValue) ? 600 : windowInfo.Width;
var windowHeight = (windowInfo.Height == int.MinValue) ? 800 : windowInfo.Height;
chromiumWebBrowser.Invoke(new Action(() =>
{
var owner = chromiumWebBrowser.FindForm();
chromiumBrowser = new ChromiumWebBrowser(targetUrl)
{
LifeSpanHandler = this
};
chromiumBrowser.SetAsPopup();
var popup = new Form
{
Left = windowX,
Top = windowY,
Width = windowWidth,
Height = windowHeight,
Text = targetFrameName
};
owner.AddOwnedForm(popup);
//popup.Controls.Add(new Label { Text = "CefSharp Custom Popup" });
popup.Controls.Add(chromiumBrowser);
popup.Show();
}));
newBrowser = chromiumBrowser;
return false;
}
}

Related

problem of getting url of loading html page (c#)

Well,
I develop a native browser and i've got a problem with a site navigated on this browser.
An input["type"]-button click post an httprequest to obtain and show an other page in a new tab (onglet).
I'm trying several methods but the TabPageof webBrowser is blank and I've got a IE explorer window opening.
here the code
private void Browser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
webBrowser22 = (WebBrowser)sender;
if (webBrowser22.Document != null)
{
foreach (HtmlElement tag in webBrowser22.Document.All)
{
HtmlElementCollection elements = webBrowser22.Document.GetElementsByTagName("input");
for (int i = 0; i < elements.Count; i++)
{
HtmlElement el = elements[i];
string elType = el.GetAttribute("type");
switch (elType)
{
case "radio":
case "checkbox":
case "button":
{
el.MouseUp += new HtmlElementEventHandler(link_MouseUpPup);
}
}}}}
private void link_MouseUpPup(object sender, HtmlElementEventArgs e)
{
this.tb2 = new System.Windows.Forms.TabPage();
this.webBrowser221 = new System.Windows.Forms.WebBrowser();
var linky = (HtmlElement)sender;
mshtml.HTMLAnchorElement ba = (mshtml.HTMLAnchorElement)linky.DomElement;
// if ((ba.target != null && ba.target.ToLower() == "_blank") || e.ShiftKeyPressed || e.MouseButtonsPressed == MouseButtons.Middle)
//if (Regex.Match(e.ReturnValue.ToString(), "http:").Value != null || Regex.Match(e.ReturnValue.ToString(), "https:").Value != null)
tabControl1.Controls.AddRange(new Control[] { this.tb2 });
tb2.Controls.AddRange(new Control[] { this.webBrowser221 });
webBrowser221.Dock = DockStyle.Fill;
1ERE METHODE----
//webBrowser221.Navigate(HttpContext.Current.Request.Url.AbsoluteUri);
2EME METHODE----
//webBrowser221.Navigate(ba.href);
3EME METHODE----
// webBrowser221.Navigate(HttpContext.Current.Request.ServerVariables["URL"].ToString());
4EME METHODE----
// webBrowser221.Navigate(e.ToElement.GetAttribute("onclick").ToString());
tb2.Text = e.ToElement.GetAttribute("onclick").ToString();
tb2.ToolTipText = webBrowser221.StatusText;
}
The problem is that I would opening the site page loading by the click input after his process (the process is been programmed in html and javascript with the function window.open and the property target="_blank") by the c# control webBrowser.
who's the problem, it's ie explorer that is opening instead of webBrowser window.
thanks your for your help.
M.A.
Finally,
I used the package reference "SHDocVm" of "Microsoft Internet Controls" and I place a function handler NewWindow3 after the case button and it's ok, a window.open() javascript function with target="_blank" opens a new page of webBrowser.
Truly yours.
M.A.

Bypass SSL Error in InAppBrowser Cordova Plugin

I have added an InAppBrowser plugin into a Cordova project to access a site and get token but while the site is opening normally in desktop browsers the same is giving error while opening from mobile browser.
Also the default native browser will ask to continue in case of SSL error but the Cordova InAppBrowser is not asking for such option and instead showing an error page. I am opening the IAB using the following code :
var iab = window.open('http://www.example.com', '_blank', 'location=yes');
Any idea on how to bypass SSL erros in InAppBrowser ?
I'm going to expand on the answer to the related question (phonegap inappbrowser https pages not loading). This pertains only to Android, sorry still working on iOS.
Add this code:
public void onReceivedSslError(WebView view,
SslErrorHandler handler, SslError error) {
Log.e("Error", "Received SSL error"+ error.toString());
handler.proceed();
}
to the InAppBrower.java file from the plugin. Specifically, it should be under the InAppBrowserClient class.
Hope this helps!
Insert Proper Code from below InAppBrowser.java in to your plugin
LOCATED IN platforms\android\src\org\apache\cordova\inappbrowser\InAppBrowser.java
Filtered code from below java code:
import android.net.http.SslError;
import android.webkit.SslErrorHandler;
#SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private boolean ignoreSSLError = false;
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if(key.equalsIgnoreCase(IGNORE_SSL_ERROR)) {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
}
return map;
}
}
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
showZoomControls = true;
openWindowHidden = false;
ignoreSSLError = false;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
Boolean SSLError = features.get(IGNORE_SSL_ERROR);
if(SSLError != null){
ignoreSSLError = SSLError.booleanValue();
}
Boolean zoom = features.get(ZOOM);
if (zoom != null) {
showZoomControls = zoom.booleanValue();
}
Boolean hidden = features.get(HIDDEN);
if (hidden != null) {
openWindowHidden = hidden.booleanValue();
}
Boolean hardwareBack = features.get(HARDWARE_BACK_BUTTON);
if (hardwareBack != null) {
hadwareBackButton = hardwareBack.booleanValue();
}
Boolean cache = features.get(CLEAR_ALL_CACHE);
if (cache != null) {
clearAllCache = cache.booleanValue();
} else {
cache = features.get(CLEAR_SESSION_CACHE);
if (cache != null) {
clearSessionCache = cache.booleanValue();
}
}
}
#SuppressLint("NewApi")
public void run() {
((InAppBrowserClient) client).setSSLErrorFlag(ignoreSSLError);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
boolean ignoreSSLError = false;
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
if(this.ignoreSSLError) {
handler.proceed();
return;
}
else{
super.onReceivedSslError(view, handler, error);
}
}
public void setSSLErrorFlag(boolean flag) {
this.ignoreSSLError = flag;
}
}
}
THEN ADD THIS LINE IN JAVASCRIPT
var options = {
location: 'yes',
//clearcache: 'no',
toolbar: 'yes',
//clearsessioncache:'no',
zoom:'no',
ignoresslerror:'yes'
};
$scope.init = function () {
$ionicPlatform.ready(function() {
$cordovaInAppBrowser.open('https://192.168.1.80', '_blank', options)
.then(function(event) {
})
.catch(function(event) {
});
});
AFTER DONE THIS COMPILE AND EXECUTE THAT'S IT
FULL VERSION CODE
Local https links are blocked by default in InAppBrowser (links using fake SSL certificate which can't be verified by a 3rd party). Ideally, user should be given an option to proceed or cancel the request like the default desktop browsers do.
Right now, we have to additional method for accessing fake ssl in the InAppBrowser like location,zoom,hardwareback

How to have Android webview open links that are target “_blank” in default browser

How to have Android webview open links that are target “_blank” in default browser , i tried the following code but it still show all links with the webview , any one have a solution ?
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String myAlternativeURL = "http://example.com";
if (!url.equals(myAlternativeURL)) {
{
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://example.com"));
startActivity(i);
}
return true;
} else {
view.loadUrl(url);
return true;
}
}

Hide/Show WebView via Javascript in Android

In my Android web app I am trying to use javascript (from a remote HTML file) to control the visibility of an Android WebView.
I have attempted to use the addJavascriptInterface class with no success. (see http://developer.android.com/guide/webapps/webview.html)
Essentially I would like my javascript to be the following
<script>
function this() {
Android.hideView('myWebViewID');
}
window.onload = this;
</script>
Seems like it would be easy, yet all my attempts cause my app to crash during debugging.
My latest attempt was something along these lines:
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
public void hideView(View v) {
WebView webview_x = (WebView) v;
webview_x.setVisibility(View.GONE);
}
}
The problem is that you are casting the string "myWebViewID" in a WebView object.
I guess this is impossible.
To do what you want, you have to implement something like a switch that convert the string you use in JS to an ID (int) that identifies your WebView:
public class JavaScriptInterface {
private Activity mContext;
JavaScriptInterface(Activity c) {
mContext = c;
}
public void hideView(String v) {
int id = stringToId(v);
WebView webview_x = (WebView) mContext.findViewById(id);
webview_x.setVisibility(View.GONE);
}
private Integer stringToId(String str) {
if(str.equals("stringForId1") {
return R.id.webView1;
} else if(str.equals("stringForId2") {
return R.id.webView2;
} else if(...) {
....
} else {
return null;
}
}
}
This is the solution:
WebView:
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(new CustomWebChromeClient());
mWebView.addJavascriptInterface(new CustomJavaScriptInterface(),
"android");
mWebView.loadUrl("file:///android_asset/www/test.html");
CustomeJavascriptInterface:
final class CustomJavaScriptInterface {
public void hide() {
mHandler.post(new Runnable() {
public void run() {
mWebView.setVisibility(View.INVISIBLE);
}
});
}
}
HTML:
<div onclick="window.android.hide()">Click!</div>
You should be fine with this!
Note that you cannot access the webview and change its visibility without a handler!
Hope this helps!

Problem adding plus one button on XUL window

I am trying to add plus one button on a XUL window, but I get this error:
Error: Permission denied for <https://plusone.google.com> to call method ChromeWindow.postMessage
Source file: https://ssl.gstatic.com/webclient/js/gc/22431124-0a127465/googleapis.client__plusone.js
Line: 14
I am adding an iframe to https://plusone.google.com/u/0/_/+1/fastbutton?url= ...
Is there a way to add the +1 button on a XUL window and make it accept the postMessage?
The addon I am trying to develop is in the image bellow. The only problem is that it does not register the click due the permission.
bootstrap.js (bootstrap-vsdoc.js)
/// <reference path="bootstrap-vsdoc.js" />
/// <summary>
/// Made by Bruno Leonardo Michels
/// </summary>
var watcher = Components.classes["#mozilla.org/embedcomp/window-watcher;1"]
.getService(Components.interfaces.nsIWindowWatcher);
var listenOpen = {
observe : function(cWindow, cEvent) {
if (cEvent != "domwindowopened") return;
cWindow.addEventListener("load", start, false);
}
};
function startup(data, reason) {
watcher.registerNotification(listenOpen);
var mWindows = watcher.getWindowEnumerator();
while (mWindows.hasMoreElements()) {
start(mWindows.getNext());
}
}
function shutdown(data, reason) {
watcher.unregisterNotification(listenOpen);
var mWindows = watcher.getWindowEnumerator();
while (mWindows.hasMoreElements()) {
end(mWindows.getNext());
}
}
function install(data, reason) {
}
function uninstall(data, reason) {
}
/// #region Methods
function getWindow(cWindow)
{
try
{
if (cWindow instanceof Components.interfaces.nsIDOMEvent)
{
cWindow = cWindow.currentTarget;
}
if (cWindow.document.documentElement.getAttribute("windowtype") != "navigator:browser")
return;
}
catch(ex) { }
return cWindow;
}
function ajaxGet(cWindow, url, cb)
{
var xmlhttp;
xmlhttp = new cWindow.XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
cb(xmlhttp);
}
};
xmlhttp.send();
}
var eventList = [];
function bind(gBrowser, cWindow, target, eventName, fn)
{
var ev = function(e) { fn(gBrowser, cWindow, e); };
eventList.push(ev);
target.addEventListener(eventName, eventList[eventList.length-1], false);
}
function unbind(target, eventName, fn)
{
var b = target.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
b(target, eventName, fn);
}
function unbindAll(target, eventName)
{
for (var i in eventList)
{
unbind(target, eventName, eventList[i]);
}
}
/// #endregion
/// #region Events
function start(cWindow) {
cWindow = getWindow(cWindow);
if (!cWindow) return;
with (cWindow)
{
bind(gBrowser, cWindow, gBrowser.tabContainer, "TabAttrModified", tabChange);
var window = cWindow;
var document = cWindow.document;
var url = window.location.href;
if (!/^http/i.test(url))url="http://www.orkutmanager.net/";
var urlE= window.encodeURIComponent(url);
var iconsBar = document.getElementById("urlbar-icons");
function insScript(w)
{
var sc = document.createElement("script");
sc.src = "https://apis.google.com/js/plusone.js";
sc.type= "text/javascript";
sc.setAttribute("extension", "plusoneany");
(document.lastChild).appendChild(sc);
}
insScript(this);
insScript(this.parent);
insScript(this.top);
var button = document.createElement("iframe");
button.id = "extensions.plusoneany.button";
button.setAttribute("src", "https://plusone.google.com/u/0/_/+1/fastbutton?url=" + urlE +
"&size=small&count=true&hl=en-US&_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe");
button.setAttribute("class", "urlbar-icon extensions-plusoneany");
button.setAttribute("style", "border:0;padding:0;margin:0;width:70px;height:16px;");
iconsBar.insertBefore(button, iconsBar.lastChild);
}
}
function end(cWindow) {
try
{
unbindAll(gBrowser.tabContainer, "TabAttrModified");
}
catch(ex){}
try
{
var elements = cWindow.document.getElementsByClassName("extensions-plusoneany");
for (var i in elements)
{
elements[i].parentNode.removeChild(elements[i]);
}
}
catch(ex){}
}
function tabChange(gBrowser, cWindow, e) {
var win = gBrowser.selectedBrowser.contentWindow;
var uns = gBrowser.selectedBrowser.contentWindow.wrappedJSObject;
uns.clearTimeout(uns.PlusOneAnyTimeout);
uns.PlusOneAnyTimeout = uns.setTimeout(function() {
var url = win.location.href;
if (!/^http/i.test(url))url="http://www.orkutmanager.net/";
var urlE= uns.encodeURIComponent(url);
try {
var ifr = cWindow.document.getElementById("extensions.plusoneany.button");
ifr.setAttribute("src", "https://plusone.google.com/u/0/_/+1/fastbutton?url=" + urlE +
"&size=small&count=true&hl=en-US&_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe");
}catch(ex){}
}, 500);
}
/// #endregion
#systempuntoout is right that, theoretically, setting the iframe type attribute to "content" should fix this. I've had problems with this in the past, however. It might work, but I think XUL is a bit buggy in this respect. If it were me I'd embed a XUL <browser> element instead of a XUL <iframe> and load a static HTML page into the browser (i.e. by calling browser.loadURI) which contains the code I want to run (in this case the iframe with src set to "https://plusone.google.com..."). That way your code will run as real content, just like it would in the main browser content window.
You can write the HTML page to disk (since part of the iframe source is generated dynamically) and then reference it with a file:// URL. Since the code will be pretty short in this case, you can even try using a data URI, which would save you from having to write the temporary file to disk.
In other words you'd create an HTML file (in memory or on disk) with:
<html>
<body>
<iframe src="https://plusone.google.com..." />
</body>
</html>
Then you'd create a <browser> element just like you do now for the iframe, insert it into your XUL document and call loadURI() on it, referencing the HTML file (via file: or data: URI).
I would try to specify the type adding this line:
ifr.setAttribute("type","content");
I think this might be helpful, it could be the issue you are having.
How do you use window.postMessage across domains?
Extremely evil answer, but cant you just get the content of https://apis.google.com/js/plusone.js and then eval it? It's Google, what could go wrong ;]

Categories

Resources