Search code examples
javascriptiframetypescriptsandbox

TypeScript : IFrame sandbox property undefined, DOMSettableTokenList has no constructor


I am creating an iFrame element in type script:

var iFrameElement : HTMLIFrameElement = document.createElement("iframe");
iFrameElement.sandbox.add('allow-forms');
iFrameElement.sandbox.add('allow-scripts'); 
iFrameElement.sandbox.add('allow-same-origin');

However, the sandbox property is undefined, so the add(value: string) here fails.

I cannot figure out how to instantiate the sandbox property either, here's the interface as defined in lib.d.ts:

interface HTMLIFrameElement {
    sandbox: DOMSettableTokenList;
}
interface DOMSettableTokenList extends DOMTokenList {
    value: string;
}
interface DOMTokenList {
    length: number;
    contains(token: string): boolean;
    remove(token: string): void;
    toggle(token: string): boolean;
    add(token: string): void;
    item(index: number): string;
    [index: number]: string;
    toString(): string;
}

I am thinking there is just some syntax I don't know how to use here, or there is some other trick to get this working. I searched extensively on this site and the internet at large, however results were not particularly helpful.

The answer here unfortunately does not work in TypeScript (Type 'String' is missing property 'value' from type 'DOMSettableTokenList') which makes me want to cast some object to that type. I see this guy appears to have re-implemented the type, but this seems too hacky to me right now.

Help me stackoverflow, you're my only hope.


Solution

  • Generally, if you are figuring out some browser specific implementations, I'd suggest you to cast (change type) to any, so you can write even:

    (<any>iFrameElement).foo = "";
    

    ... but make some catching in your code.

    This will allow you to use this for IE:

    iFrameElement.sandbox.add('allow-forms');
    iFrameElement.sandbox.add('allow-scripts');
    

    And this for Chrome:

    (<any>iFrameElement).sandbox = "allow-forms allow-scripts";