WebBrowser control and JavaScript errors - c#

When I access the page with the browser (ie9), the browser is rendering ok.
When I use the WebBrowser control I have JavaScript errors.
I know I can suppress the scripts errors, but I want them to run correctly, because they affect the rendering and the functionality of the page.
How can I solve this problem ? Can I integrate IE9 directly in the Windows Form and use similar methods like with the WebBrowser control (navigate,get id, invoke click) ?
Thanks.

What I would do is assign an object to webbrowser.ObjectForScripting and then inject a javascript function that assigns windown.onerror to a wrapper that calls the external script in the host app. Like:
window.onerror = function(message, url, lineNumber)
{
window.external.errorHandler(message, url, lineNumber);
}
Refere to:
http://notions.okuda.ca/2009/06/11/calling-javascript-in-a-webbrowser-control-from-c/

If you have IE9 installed, the WebBrowser will still use IE7 mode unless you override this behaviour with a registry setting - as described in this StackOverflow answer. This is the most likely cause of the JavaScript errors you're getting in the WebBrowser (because you're not seeing the same errors in IE9).
You can make the registry setting using the following c# code (which sets IE10 mode if Windows 8 is detected) and changing app-name.exe to match your own application. You should add an error handler for the case where there are insufficient privileges (admin privileges are required to write to this registry key).
string installkey = #"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string entryLabel = "app-name.exe";
System.OperatingSystem osInfo = System.Environment.OSVersion;
string version = osInfo.Version.Major.ToString() + '.' + osInfo.Version.Minor.ToString();
uint editFlag = (uint)((version == "6.2") ? 0x2710 : 0x2328); // 6.2 = Windows 8 and therefore IE10
RegistryKey existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, false); // readonly key
if (existingSubKey.GetValue(entryLabel) == null)
{
existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, true); // writable key
existingSubKey.SetValue(entryLabel, unchecked((int)editFlag), RegistryValueKind.DWord);
}

You can use the following code line to get rid of those types of errors:
webBrowser1.ScriptErrorsSuppressed = true;
It will prevent getting JavaScript errors.

So i know the post is old, but it was a recent problem for me and i had to do some serious digging and thinking outside the box.
basically like most replies here - you cannot alter the webbrowser control to use the most recent IE engine. mine uses IE7 by default, i have seen some replies that basically changes/ adds stuff to registry, am always not comfy when it comes to the registry, a cleaner way to address this issue would be to append code on your website that forces it to use the most current IE engine on any pc and works like a charm.
if you have access to the web.config file of the page you intend to browse, simple append:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
</system.webServer>
and your site would force webbrowser control to run the most current IE engine on your computer. Other options are found here:
https://www.leapinggorilla.com/Blog/Read/1016/ie-ate-my-css---disabling-compatability-mode
I should state that this would only work if you have access to the page / web.config of the website/ application you are trying to access- which was my case.

THe WebBrowser control uses IE7. So if there is a problem then your script does not work for IE7 and you will have to fix that.
You cannot integrate IE9 as it depends on it being installed on the computer and not everyone has IE9 installed.

As a help to whoever else may have this problem, I tried all these things and nothing worked for me. Here's what does work. I am not sure exactly what causes this error, but apparently when you just press "F5" in VS to debug your app, it runs YourProject.vshost.exe as the process name. If you run the same app from the command line, it will show up as YourProject.exe, and the javascript errors vanish. I think IE sees the app running visa via VSHOST and decides this is fishy and disables javascript from loading correctly.
So... go into your project setting for your executable.
Select "Debug" options.
Select "Start External Program".
Browse to and select Debug\YourProgram.exe (NOT YourProgram.vshost.exe).
Save, recompile, and hit F5.
Everything should work as per usual now, and Visual Studio even attaches to the process for you automatically.
Enjoy!
Grego

Related

C# WebBrowser Control Enhanced Protected Mode

I am trying to access a webpage (that is not under my control) namely allscripts sandbox via a WebBrowser control. My computer's internet explorer is correctly set up for said webpage (Added in Trusted Sites, Allowed and installed all active-x addons, running in compatibility mode, etc).
The webbrowser control displays the following error:
This webpage wants to run 'Some ActiveX control' which isn't compatible with Internet Explorer's enhanced security features. If you trust this site you can disable Enchanced Protected Mode for this site and allow the control to run.
I have not enabled (to the best of my knowledge) the enhanced protected mode.
Also trying to ignore the errors and continue with log-in displays a Message
The Centricity's container for .NET-based pages failed to initialize. Make sure your .NET environment is configured to grant Full Trust to this Website.
The above was also an error on the default IE until i run the command %WINDIR%\Microsoft.NET\Framework\v2.0.50727\caspol -q -m -cg Trusted_Zone FullTrust.
I have tried various registry keys but none seemed to work.
I have also tried implementing a custom IInternetSecurityManager that Maps all urls to zone Trusted and returns URLPOLICY_ALLOW on all ProcessUrlAction calls.
Any suggestion would be appreciated.
The problem could be that webbrowser uses by default an old version of the IE. Take a look at Use latest version of Internet Explorer in the webbrowser control
The webbrowser control is ie11 wrapped with a com wrapper that throttles back ie11 to ie7 mode. There's not a lot else going on there that I can imagine would cause your issue.
Since this page works for you when you run ie11 externally then the most likely explanation seems to be your attempt to force the control into ie11 mode is the problem.
I suggest you try Mentor's code here:
Set WPF webbrowser control to use IE10 mode
Which will automate adding the name of the running program to the registry.
var pricipal = new System.Security.Principal.WindowsPrincipal(
System.Security.Principal.WindowsIdentity.GetCurrent());
if(pricipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator)) {
RegistryKey registrybrowser = Registry.LocalMachine.OpenSubKey
(#"Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
string myProgramName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var currentValue = registrybrowser.GetValue(myProgramName);
if (currentValue == null || (int)currentValue != 0x00002af9)
registrybrowser.SetValue(myProgramName, 0x00002af9, RegistryValueKind.DWord);
}
else
this.Title += " ( Первый раз запускать с правами админа )";

Disabling certificate revocation checking for an application on Windows

I have a .NET 3.5 desktop application that had been showing periodic slow downs in functionality whenever the test machine it was on was out of the office.
I managed to replicate the error on a machine in the office without an internet connection, but it was only when i used ANTS performance profiler that i got a clearer picture of what was going on.
In ANTS I saw a "Waiting for synchronization" taking up to 16 seconds that corresponded to the delay I could see in the application when NHibernate tried to load the System.Data.SqlServerCE.dll assembly.
If I tried the action again immediately it would work with no delay but if I left it for 5 minutes then it would be slow to load again the next time I tried it.
From my research so far it appears to be because the SqlServerCE dll is signed and so the system is trying to connect to get the certificate revocation lists and timing out.
Disabling the "Automatically detect settings" setting in the Internet Options LAN settings makes the problem go away, as does disabling the "Check for publishers certificate revocation".
But the admins where this application will be deployed are not going to be happy with the idea of disabling certificate checking on a per machine or per user basis so I really need to get the application level disabling of the CRL check working.
There is the well documented bug in .net 2.0 which describes this behaviour, and offers a possible fix with a config file element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<generatePublisherEvidence enabled="false"/>
</runtime>
</configuration>
This is NOT working for me however even though I am using .net 3.5.
The SQLServerCE dll is being loaded dynamically by NHibernate and I wonder if the fact that it's dynamic could somehow be why the setting isn't working, but I don't know how I could check that.
Can anyone offer suggestions as to why the config setting might not work?
Or is there another way I could disable the check at the application level, perhaps a CAS policy setting that I can use to set an exception for the application when it's installed?
Or is there something I can change in the application to up the trust level or something like that?
You can specify in code if you want to check the revocation list per application:
ServicePointManager.CheckCertificateRevocationList = false;
In this blog posting (which cites another source) you have two options: disable CRL checking system wide or per app:
Disable CRL Checking Machine-Wide Control Panel -> Internet Options ->
Advanced -> Under security, uncheck the Check for publisher's
certificate revocation option
Disable CRL Checking For a Specific .Net Application See this
Microsoft KB Article: http://support.microsoft.com/kb/936707
What solved the problem for me:
I (think I) had a problem with online revocation before, so I explicitly switched to offline. Due to to warning, I now had to change...
_ = builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(
options =>
{
options.AllowedCertificateTypes = CertificateTypes.All;
options.RevocationMode = X509RevocationMode.Offline;
}
);
... to ...
_ = builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(
options =>
{
options.AllowedCertificateTypes = CertificateTypes.All;
options.RevocationMode = X509RevocationMode.NoCheck;
}
);

How to fix "This page can't be displayed" error in ASP.NET?

I was debugging a localhost asp.net and I have made some very minor code changes and ran it again and now I get an error I have never gotten before. In nice big blue letters it tells me "This page can't be displayed".
Apart from taking everything to forumula, what do you think would cause this error and how would I go about fixing it? It offers a button that says "Fix connection problems", but this is a localhost browser, so there are no connection, really. I clicked the button anyway and it did not offer any solution. I also refreshed the page, as suggested and it did nothing.
I test my localhost in the browser and it is working.
What do you think?
If it is functioning properly for you when debugging on local host, then I would assume it is a path/file resole issue. Trying doing what was mentioned earlier, and debugging it. That is why your localhost test works, but when placed on the server for the live version, it fumbles. I do not see any other reason that may cause this. Yes, it could be a browser issue, but is not really anything specific to conclude that. What were the changes you made? Is there a way you can post the code, or some of it?
I found the offensive part of code.
The code does a check on the URL and modifies it to make sure it is correct. This messes up the localhost url. The same if statement that checks for characters in the URL now also checks that string to see if there is a "localhost" and then side-steps the code.
I had the same problem. I fixed it by next steps:
stop debug
delete solution (I think this point is optional)
get version from TFS (this point is optional with previous ;-) )
close VS
delete custom IISExpress config files in c:\Users\\Documents\IISExpress (delete whole folder)
restart computer
start VS
start Debug
Application is running.
I am using Visual Studio 2017 and I had a similar problem. I tried #Vojta Novák's instructions to no avail.
However, I did find a solution that works for me.
Right-click on the web project, select "Properties" and select the "Web" tab on the properties. Change the port number in the Project Url and click [Create Virtual Directory]. Save and run the project.
I tried deleting the IIS Express configuration folder, but it seems like no matter what I do, if I try to run the web app under the port number it was on originally, I get an error.
What is even more baffling is the fact that I only could reproduce the error when browsing the web app with IE. With Chrome, it works fine.
I get this error sometimes after I publish. I just add an empty line to my web.config. Then run the app. It now works. Then stop and undo my change to my web.config.

How to automatically bypass logon message on RDP?

I'm trying to log in to a server through remote desktop using c#. I'm able to initiate the connection using the AxMSTSCLib and the code below. However, I'm stuck on our domain's security notice.
When logging in manually it requires you to click ok on the notice before the log in completes. I have been unable to find anyway to interact with this OK button through my application. I've tried variations of SendKeys, sending key events using interop services, finding the cursor position and sending a mouse click event...
I'm running out of ideas here.
rdp.Server = server;
rdp.Domain = domain;
rdp.UserName = userName;
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = password;
rdp.StartConnected = 1;
rdp.Connect();
Thanks
Well, there is a way to do what you ask.
You will need to download a copy of Windows 7 Embedded Standard (WES7 wSP1).
WES7 contains something that other editions of Windows 7 do not - a Dialog Filter.
It runs as a service, and allows you to specify certain window events to be performed automatically, without user interaction.
The Dialog Filter Editor is installed with the Windows Embedded Standard 7 tools in the EmbeddedSDK\bin folder.
All you have to do is:
Add the service to your Windows, by copying the necessary Dialog Filter files to C:\Windows\System32. There are x86 and x64 versions, so choose the correct architecture.
Register the files, and enable the service to run automatically.
Add the ConfigurationList.xml file created with the editor to C:\ProgramData\Microsoft\DialogFilter.
This location is hidden by defeault, so make sure to show hidden files and unhide protected system files in Windows Explorer.
I've actually created the ConfigurationList.xml file already, so you can simply copy the following code and save it as "ConfigurationList.xml":
<?xml version="1.0" encoding="utf-8"?>
<CL:dialogs xmlns:CL="urn:Dialogs">
<dialog>
<ProcessImageName>rundll32.exe</ProcessImageName>
<Title>Remote Desktop Connection</Title>
<Class>#32770</Class>
<Buttons>
<Button>OK</Button>
<Button>Cancel</Button>
<Button>Close</Button>
</Buttons>
<Actions>
<Action>OK</Action>
</Actions>
</dialog>
</CL:dialogs>
As you can see, the action is set to press the OK button automatically in the RDP dialog that pops up when making an RDP connection.
More info regarding the Dialog Filter directly from MS:
https://msdn.microsoft.com/en-US/library/ff794135(v=winembedded.60).aspx
Just found a much easier way to do this:
There's a free small app called ClickOff, which works in a very similar manner to Windows Embedded Standard 7 DialogFilter.
You can download ClickOff v1.90 here.
After you install ClickOff, you can define which window to capture, and which button inside it to click. Only thing is that you must add it to your startup apps.
I have already created a clickoff.lst file which clicks OK on the 30-sec RDP timeout popup window. The file should be placed in C:\Users\USERNAME\AppData\Roaming\ClickOff. Here's the contents of the file:
1.900
WINDOWTITLE="Remote Desktop Connection" BUTTONTEXT="OK" MSGTEXT="CompName\\UserName wants to connect to this machine.\r\n\r\nClick OK to disconnect your session immediately or click cancel to stay connected.\r\n\r\nOtherwise, you will be disconnected in 30 seconds." BUTTONID="1" MSGID="65535" DLGID="0" CLKEVENT="17" CLKMETHOD="3" TIMESCLICKED="0" WAIT="0" BPOSX="0" BPOSY="0" ;
Cheers.

Local load of HTML/Javascript file in C# WebBrowser object not loading correctly?

I'm using .NET Framework 4.0 (with WPF) trying to load a local HTML file within a WebBrowser object (System.Windows.Controls.WebBrowser) with both locally embedded javascript and loaded from a remote server. The problem is, the javascript (ajax with dojo) isn't executing inside the WebBrowser object when loaded:
webBrowser.NavigateToString(LoadStringFromFile("map.html"));
However, when loaded remotely it runs just fine as follows:
webBrowser.Navigate("http://www.example.com/map.html");
Sample excerpt code of Javascript code in html file:
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=1.6"></script>
<script type="text/javascript">
dojo.require("esri.map");
var map;
var colorRGB = { "white": [255,255,255], "red": [255,0,0], "blue": [0,255,0] };
function init()
{
var streetLayer = new esri.layers.ArcGISTiledMapServiceLayer(
"http://server.arcgisonline.com/ArcGIS/rest/services/ESRI_StreetMap_World_2D/MapServer");
var extent = new esri.geometry.Extent(-140.910, 11.267, -53.019, 64.002);
map = new esri.Map("map", { extent:extent });
map.addLayer(streetLayer);
dojo.connect(map,"onLoad", processLocations);
}
Anyone have any idea what is wrong with this?
My research suggest it has to do with IE and internet zones, but have been unable to confirm it.
When i paste this into an html file and open on internet explorer, it display a message that it blocked activex/script content. Change Internet Options > Advanced > Security > Allow active content to run in files on My Computer. If the warning goes away in IE, then it should work in WebBrowser object
The WPF WebBrowser class has a static initializer that enables FEATURE_LOCALMACHINE_LOCKDOWN for the entire process. You can use CoInternetSetFeatureEnabled to turn FEATURE_LOCALMACHINE_LOCKDOWN back off on the WebBrowser Navigating event.
This solution does not require you to modify the HTML files being displayed, but does disable some security features that you probably don't want when displaying trusted local content. See http://technet.microsoft.com/en-us/library/cc782928(v=ws.10).aspx for more information about local machine lockdown.
See How to disable click sound in WebBrowser Control for PInvoke and https://github.com/TaoK/PoorMansTSqlFormatter/blob/d6b4f7bedc02ce1bf59acb16dd1f49609c216aa7/PoorMansTSqlFormatterDemo/FrameworkClassReplacements/CustomContentWebBrowser.cs for an example usage.
Here is my solution for preventing scriptwarnings:
WebBrowser.ScriptErrorsSuppressed = true;
Also I've put my website as a trusted website in my Internet Settings, I don't know if that helps but the scriptErrorsSuppressed property was enough for me.
Hope this helps.
For me, the problem was:
Steps to enable ActiveX controls in Internet Explorer:
1.Select Tools --> Internet Options menu from the Internet Explorer.
2.Select the Security tab from the Internet Options dialog.
3.Select the appropriate Web content zone and click Custom Level.
4.Make the following options available under ActiveX controls and plug-ins to either enableor Prompt:1.Download signed ActiveX controls
2.Run ActiveX controls and plug-ins
3.Script ActiveX controls marked safe for scripting
5.Click Ok to save the security settings.
6.Click OK to save and close the Internet Options dialog.
Then click don't show this message again.

Categories

Resources