dotnet/wpf · error · ArgumentException
SR.NeedToBeComVisible
Error message
SR.NeedToBeComVisible
What it means
Setting WebBrowser.ObjectForScripting throws ArgumentException (SR.NeedToBeComVisible) when the object's type is not visible from COM. The object is exposed to page JavaScript through COM interop, so its class must be marked [ComVisible(true)].
Solutions
- Decorate the class with [ComVisible(true)] (public class) before assigning it.
- Use a dedicated public script-bridge class instead of anonymous/internal types.
- Verify with Marshal.IsTypeVisibleFromCom(obj.GetType()) before assignment.
- Ensure the assembly/type is not blocked by visibility settings (internal nested classes need to be made public).
Example fix
// before
webBrowser.ObjectForScripting = new { Notify = (Action<string>)(s => ...) };
// after
[ComVisible(true)]
public class ScriptBridge { public void Notify(string s) { ... } }
webBrowser.ObjectForScripting = new ScriptBridge(); Defensive patterns
Strategy: validation
Validate before calling
if (!Marshal.IsTypeVisibleFromCom(obj.GetType())) throw new ArgumentException("ObjectForScripting must be ComVisible"); Type guard
bool IsComVisible(object o) => o != null && Marshal.IsTypeVisibleFromCom(o.GetType());
Try / catch
try { webBrowser.ObjectForScripting = bridge; } catch (ArgumentException) { /* apply [ComVisible(true)] and re-init */ } Prevention
- Always mark script bridge classes [ComVisible(true)] public
- Test COM exposure with Marshal.IsTypeVisibleFromCom in unit tests
When it happens
Trigger: Assigning an instance of a plain class without [ComVisible(true)] to webBrowser.ObjectForScripting; assigning anonymous or generic types; the type becoming COM-invisible after assembly attributes changed.
Common situations: Forgetting the [ComVisible(true)] attribute on the scripting bridge class; passing a lambda-created or internal type; .NET version/registration changes affecting COM visibility defaults.
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
AI-assisted analysis of dotnet/wpf@81131a70a4 (2026-09-14).
Data as JSON: /api/errors/a793e8b2862377d8.
Report an issue: GitHub.
Appendix: source
Thrown at src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Controls/WebBrowser.cs:432
public object ObjectForScripting
{
get
{
VerifyAccess();
return _objectForScripting;
}
set
{
VerifyAccess();
if (value != null)
{
Type t = value.GetType();
if (!Marshal.IsTypeVisibleFromCom(t))
{
throw new ArgumentException(SR.NeedToBeComVisible);
}
}
_objectForScripting = value;
_hostingAdaptor.ObjectForScripting = value;
}
}
/// <summary>
/// The HtmlDocument for page hosted in the html page. If no page is loaded, it returns null.
/// </summary>
public object Document
{
get
{
VerifyAccess();
View on GitHub (pinned to 81131a70a4)