Suppress Script errors in WebBrowser control but still allow popups - javascript

I am getting vaious script errors when I use a WebBrowser Control to view web pages in my WPF application. To supress these I used the 'Silent' method as outlined in this link: http://social.msdn.microsoft.com/Forums/vstudio/en-US/4f686de1-8884-4a8d-8ec5-ae4eff8ce6db/new-wpf-webbrowser-how-do-i-suppress-script-errors?forum=wpf
void wbMain_Navigated(object sender, NavigationEventArgs e)
{
SetSilent(WebBrowser, true);
}
public static void SetSilent(WebBrowser browser, bool silent)
{
if (browser == null)
throw new ArgumentNullException("browser");
FieldInfo webBrowserInfo = browser.GetType().GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
object comWebBrowser = null;
if (webBrowserInfo != null)
comWebBrowser = webBrowserInfo.GetValue(browser);
if (comWebBrowser != null)
comWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, comWebBrowser, new object[] { silent });
}
But the problem now is that because the "Silent" property has been set none of my web pages right click options work. (There are many right click options on my flash website that pop up various menus).
If I don't use the workaround above then the right click action brings up script error:
"An error has occurred in the script on this page"
How can I get around this?

Related

opening link in external browser from page in WebView

I'm developing an angular website which is loading in an app from a WebView, and there is only one of the links in it that has to be opened outside of the app (external browser)
I need a way to handle this from JavaScript not putting extra work to the android side.
and i have already tried some ways including:
window.open("url","_system")
(navigator as any).app.loadUrl("http://google.com", {openExternal : true});
Well, there is no such thing
instead it must be handled from android application code. you can add a parameter to the url when u need it to open in external browser, ( here it is external=true ) and then check for that parameter in your webview url loading as below:
webView.setWebViewClient(new WebViewClient(){
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if((String.valueOf(request.getUrl())).contains("external=true")) {
Intent intent = new Intent(Intent.ACTION_VIEW, request.getUrl());
view.getContext().startActivity(intent);
return true;
} else {
view.loadUrl(String.valueOf(request.getUrl()));
}
return true;
}
});

How to invoke Eclipse RCP perspective ( Java Class method) from JavaScript code?

I would like to invoke or open Perspective(or Views) from JavaScript function.
I have an Eclipse RCP application, where I have embedded My HTML page. On button click from HTML page, i would like to open Eclipse RCP perspective or View.
I have tried as shown below from javascript function
function populateGeometryData(){
alert('Inside populateGeometryData() function !!!!!');
var geoMetryDataClass = Java.type("com.test.app.ui.view.PageView");
geoMetryDataClass.populateGemetryData("TestVal");
}
Where PageView is one of my perspective. But I got " Uncaught ReferenceError: Java is not defined" .
I think, this error is because of Chrome no longer supports NPAPI (technology required for Java applets). So, is there any other ways to invoke Java class method from JavaScript?
Below is how, I am launching my HTML page from Eclipse RCP code.
#Override
public void createPartControl(Composite parent) {
String user = ExecuteRestService.getLoggedInUser();
System.out.println("Login User "+user);
String html = "/Pages/index.html";
Bundle appBundle = FrameworkUtil.getBundle(this.getClass());
if(appBundle == null) {
System.out.println("bundle is null");
return;
}
URL url = FileLocator.find(appBundle, new Path(html), null);
try {
url = FileLocator.toFileURL(url);
} catch (IOException e) {
// TODO Auto-generated catch block#*
e.printStackTrace();
}
Browser browser = new Browser(parent, SWT.None);
String urlVal = url.toString()+"?LoginUser="+user;
browser.setUrl(urlVal);
}
I am looking some suggestions to call Java Class Method or to Invoke Eclipse RCP perspective from JavaScript function.
Thank you in advance.
UPDATE
As Greg suggested in comments section, using "BrowserFunction" we can call Java class method in Eclipse RCP from javascript if you are using SWT browser to launch your HTML page.
new BrowserFunction(browser, "populateGeometricData")
{
#Override
public Object function(Object[] objects)
{
if(objects.length == 0) {
System.out.println(" array is zero");
}else {
System.out.println("Call from Javascript"
+ objects.length);
System.out.println("Request Id "+ objects[0]);
}
return null;
}
};

Android Web-view Error I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError:

I have a web-service In that I have added bar-code reader for android
So with the Help of JavaScript I am calling my bar-code reader from web-view
So for that I followed this
and designed on server side...
I have Given this
at JavaScript
function mybarcd() {
MyApp.mybarcdt();
}
function actfromAnd(msg){
document.getElementById("brcd").value = msg;
}
at HTML/PHP
<div class="data">
<input id="brcd" type="text" value=""/>
<button type="button" onClick="mybarcd()">SCAN</button>
</div>
On Android side
In webview
webView.addJavascriptInterface(new WebAppInterface(this), "MyApp");
and new js interface
#JavascriptInterface
public void mybarcdt() {
IntentIntegrator intentIntegrator = new IntentIntegrator(Main_A.this);
intentIntegrator.setBeepEnabled(true);
intentIntegrator.setOrientationLocked(true);
intentIntegrator.setPrompt("Scan Barcode");
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
Log.d("ScanActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("ScanActivity", "Scanned");
String bcval = result.getContents();
if (android.os.Build.VERSION.SDK_INT < 19) {
webView.loadUrl("javascript:actfromAnd(\""+bcval+"\")");
}else{
webView.evaluateJavascript("javascript:actfromAnd(\""+bcval+"\")", null);
}
System.out.println("javascript:actfromAnd(\""+bcval+"\")");
}
} else
super.onActivityResult(requestCode, resultCode, data);
}
My Problem is that Its working fine in a single Html/PHP file with Js on same page or separate page I have tested its scanning and Updating the value in input box...
But its not working since I have using multiple pages or frame in one webview...
its missing JS value... How ever form server its opening scanner at on-click... but after scanning the value is not passing to the input box with JS I am getting this error.....
I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError: actfromAnd is not defined", source: (1)
Update
1)I hava Tried this in Static Page with JS in side that PHP/HTML page
2)I also tried with same in a static Page with JS seperate page
On the above two conditions its worked fine
But In my web-service I have Given Same JS file which is running successfully in Static page I have a single JS file for My Webservice and Static page its working fine in static but not working in MY webservice live.. How ever JS is loading Because on click its wokring from that JS and its opening Camera
But responce after scanning its not going to web input
I understand that I am getting Error Because...
In my Live Page I have a MainMenu Inside that menu when I select a application its loading in iframe So my Android Activity responce after scanning Is pinging to that Mainmenu page But for menu there is no Js function named actfromAnd So I am getting Error...
Here I can't give URL of that particular page(iframe) Because of depending on the menus it will change I can Give Only Login or MainMenu link directly.but not for a particular page inside the menu
Can Any one suggest me on this kind...
Add this script in Web-service at your Parent Menu which has your iframe or iframes
<script>
function actfromAnd(msg){
window.frames['yourExactframe'].document.getElementById("brcd").value = msg;
}
</script>
If you are using same in more than one frame then declare your frame name globally
I tried your Code Working Fine... In my example Frame Hope It works fine for you
Nice question....
You should execute the javascript when the page is loaded
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:myFunction()");
}
});
The code will be executed and will find your javascript function. The way you are doing now does not wait.

GetElementById does not locate elements currently visible in webbrowser

I'm trying to automate navigation through a webpage that uses HTML and JavaScript. I'm using C# to do this and have not worked with it for a long time so am rather rusty, this is the best I've managed to come up with (including trying webBrowserEvents2).
What I have so far is attached below. Everything runs ok until the 5th while statement which continues as an infinite loop even though element in question is visible in the web browser.
I've commented-out the 5th while statement and everything below it in the first method and then used the second method to list all the elements in the web browser the have IDs. I've found all the elements listed belong to the previous page even though it is no longer visible.
This issue has not been present in the earlier while statements so I am not sure what the problem could be. I have tried refreshing, updating and invalidating the web browser and this has not worked. What is causing this to happen?
//Start navigation
private void goButton_Click(object sender, EventArgs e)
{
//Load Login page
webBrowser1.Navigate(site);
while (webBrowser1.Document.GetElementById("gwt-uid-27") == null)
{
Application.DoEvents();
}
Console.WriteLine("Login page loaded");
//Login
webBrowser1.Document.GetElementById("gwt-uid-27").SetAttribute("value", password);
webBrowser1.Document.GetElementById("gwt-uid-37").InvokeMember("click");
while (webBrowser1.Document.GetElementById("popup_0") == null)
{
Application.DoEvents();
}
while (webBrowser1.Document.GetElementById("popup_0") != null)
{
Application.DoEvents();
}
Console.WriteLine("Login Successful");
//Navigate to timesheets page
webBrowser1.Document.GetElementById("gwt-uid-48").InvokeMember("click");
while (webBrowser1.Document.GetElementById("add-time") == null)
{
Application.DoEvents();
}
//Go to 'Select date' page
webBrowser1.Document.GetElementById("add-time").InvokeMember("click");
while (webBrowser1.Document.GetElementById("gwt-uid-120") == null)
{
Application.DoEvents();
}
//Enter date
string date = String.Format("{0:yyyy-M-d}", dateTimePicker);
webBrowser1.Document.GetElementById("gwt-uid-120").SetAttribute("value", date);
webBrowser1.Document.GetElementById("gwt-uid-125").InvokeMember("click");
}
private void secondary_Click(object sender, EventArgs e)
{
var v = webBrowser1.Document.All;
List<string> c = new List<string>();
foreach (HtmlElement h in v)
{
if (h.Id!=null) c.Add(h.Id);
}
Console.WriteLine("done");
}
Since posting this I've written the same method in VBA with no issues whatsoever and can't figure out why.

C# WPF Web Browser Control Security Error

I'm currently having trouble to nagivate to local file which have the index.html.
I had try to copied the URL link to firefox and google chrome and it worked. But when I'm trying to navigate to the URL link with C# Web Browser Control, it gave me a black screen with
Fatal: loading error (Security Error)
which I feel very weird.
Here is the example link: file://127.0.0.1/c$/Users/Marcus/Desktop/03%20Virtual%20Tour/dataranlang/index.html
Here is my code that used to called for the URL link in C# Web Browser Control:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
namespace Perak360
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.WB.Loaded += (s, e) =>
{
// get the underlying WebBrowser ActiveX object;
// this code depends on SHDocVw.dll COM interop assembly,
// generate SHDocVw.dll: "tlbimp.exe ieframe.dll",
// and add as a reference to the project
var activeX = this.WB.GetType().InvokeMember("ActiveXInstance",
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, this.WB, new object[] { }) as SHDocVw.WebBrowser;
// now we can handle previously inaccessible WB events
activeX.FileDownload += activeX_FileDownload;
};
this.Loaded += (s, e) =>
{
try
{
this.WB.Source = new Uri(new System.IO.FileInfo(#"C:\Users\Marcus Tan\Documents\Visual Studio 2013\Projects\Perak360\Perak360\Perakin360 Offline (Final)\index.html").FullName);
//this.WB.Navigate(Properties.Settings.Default.WebBrowserPath);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
};
}
void activeX_FileDownload(bool ActiveDocument, ref bool Cancel)
{
Cancel = true;
}
private void CloseWindow(object sender, TouchEventArgs e)
{
Application.Current.Shutdown();
}
}
}
I know that if i changed the URL link to file://C:/Users/Marcus%20Tan/Desktop/03%20Virtual%20Tour/dataranlang/index.html it may work, but there will be a javascript prompt out which ask user to enable the blocked content which I don't want it to be appear.
Any clue what wrong with my URL link or code which it gave me a black screen without the loading error screen? I had try to search online for solution and try to set the Internet Security setting, but none of it work.
Please guide me through this.

Categories