Skip to content

Commit

Permalink
feat: add trusted types support "angular-extensions#elements"
Browse files Browse the repository at this point in the history
  • Loading branch information
tomastrajan committed Mar 2, 2024
1 parent d84102e commit f07ed3e
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
8 changes: 8 additions & 0 deletions projects/elements/jest.setup.ts
@@ -1,3 +1,11 @@
import 'jest-preset-angular/setup-jest.mjs';

declare const ngDevMode: boolean;

// Globals mocks
(window as any).trustedTypes = {
createPolicy: (name: string) => ({
createScript: (script: string) => script,
createScriptURL: (url: string) => url,
}),
};
Expand Up @@ -15,6 +15,7 @@ import {
LAZY_ELEMENT_ROOT_OPTIONS,
LAZY_ELEMENTS_REGISTRY,
} from './lazy-elements.tokens';
import { getPolicy } from './trusted-types';

import './ng-dev-mode';

Expand Down Expand Up @@ -132,7 +133,7 @@ export class LazyElementsLoaderService implements OnDestroy {
if (isModule) {
script.type = 'module';
}
script.src = url;
script.src = getPolicy().createScriptURL(url);
const onLoad = () => {
if (afterLoadHook) {
this.handleHook(afterLoadHook, tag)
Expand Down
34 changes: 34 additions & 0 deletions projects/elements/src/lib/lazy-elements/trusted-types.ts
@@ -0,0 +1,34 @@
export declare interface TrustedTypePolicy {
createScriptURL(url: string): string;
}

export declare interface TrustedTypePolicyFactory {
createPolicy(
policyName: string,
policyOptions: {
createScriptURL?: (url: string) => string;
}
): TrustedTypePolicy;
}

let policy: TrustedTypePolicy | null | undefined;

export function getPolicy(): TrustedTypePolicy | null {
if (policy === undefined) {
policy = null;
if (typeof window !== 'undefined') {
const ttWindow = window as unknown as {
trustedTypes?: TrustedTypePolicyFactory;
};
if (ttWindow.trustedTypes !== undefined) {
policy = ttWindow.trustedTypes.createPolicy(
'angular-extensions#elements',
{
createScriptURL: (url: string) => url,
}
);
}
}
}
return policy;
}

0 comments on commit f07ed3e

Please sign in to comment.