Skip to content

instanceof operator doesn't work for objects exposed to JS #103

Open
@arekdygas

Description

@arekdygas

Bug Report

Prerequisites

  • Can you reproduce the problem in a MWE?
  • Are you running the latest version of AngleSharp?
  • Did you check the FAQs to see if that helps you?
  • Are you reporting to the correct repository? (there are multiple AngleSharp libraries, e.g., AngleSharp.Css for CSS support)
  • Did you perform a search in the issues?

For more information, see the CONTRIBUTING guide.

Description

As title says - instanceof operator doesn't work e.g. for Window, Element, etc.

Steps to Reproduce

var config = Configuration.Default.WithJs();
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(req => req.Content("")).ConfigureAwait(false);
Console.WriteLine(document.ExecuteScript("window instanceof Window"));
Console.WriteLine(document.ExecuteScript("document.createElement('div') instanceof Element"));

Expected behavior:

Console output: twice True

Actual behavior:

Console output: twice False

Environment details:

.NET Framework 4.8, Win 10

Possible Solution

I have to admit here, that I'm not sure how to fix it properly. Simple fix, which works in my case, is quite easy and includes adding [Symbol.hasInstance] implementation to DomConstructorInstance, but I have no idea if this a correct way, and even if it is, then if my implementation would not fail for some cases.

My solution

In DomConstructorInstance constructor, the following code was added

var hasInstanceFunction = new ClrFunction(Engine, "[Symbol.hasInstance]", (thisObj, args) => IsInstanceOf(args[0], type), 1, PropertyFlag.None);
var hasInstanceProperty = new PropertyDescriptor(hasInstanceFunction, false, false, false);
FastSetProperty(Jint.Native.Symbol.GlobalSymbolRegistry.HasInstance, hasInstanceProperty);

EDIT: changed PropertyFlag.Configurable to PropertyFlag.None

And IsInstance method:

private JsValue IsInstanceOf(JsValue arg, Type type)
{
    return type.IsInstanceOfType(arg.ToObject());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions