Skip to content

Commit af9feb4

Browse files
bjarkleralexeagle
authored andcommitted
feat(karma): use Trusted Types policy when loading scripts for Karma
When the Karma plugin is used in a testing environment that enforces Trusted Types, its loadFile functionality currently fails due to a Trusted Types violation when assigning to script.textContent. This makes it impossible to use the plugin with integration tests that ensure an application is compatible with Trusted Types. This is fixed by creating a Trusted Types policy specifically for the Karma plugin, and use it to promote any loaded scripts to a TrustedScript before assigning to script.textContent. This is done in a way that is backwards compatible: - The policy is `null` in browsers that don't yet support Trusted Types, in which case the original script string is used as before. - When Trusted Types are supported in the browser but not enforced by the application, the browser treats the TrustedScript as if it were a string when it is assigned to script.textContent.
1 parent 4fc0cc4 commit af9feb4

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

packages/karma/index.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,31 @@ function initConcatJs(logger, emitter, basePath, hostname, port) {
5555
// global variables, even with 'use strict'; (unlike eval).
5656
bundleFile.content = `
5757
(function() { // Hide local variables
58+
// Use policy to support Trusted Types enforcement.
59+
var policy = null;
60+
if (window.trustedTypes) {
61+
try {
62+
policy = window.trustedTypes.createPolicy('bazel-karma', {
63+
createScript: function(s) { return s; }
64+
});
65+
} catch (e) {
66+
// In case the policy has been unexpectedly created before, log the error
67+
// and fall back to the old behavior.
68+
console.log(e);
69+
}
70+
}
5871
// IE 8 and below do not support document.head.
5972
var parent = document.getElementsByTagName('head')[0] ||
6073
document.documentElement;
6174
function loadFile(path, src) {
75+
var trustedSrc = policy ? policy.createScript(src) : src;
6276
try {
6377
var script = document.createElement('script');
6478
if ('textContent' in script) {
65-
script.textContent = src;
79+
script.textContent = trustedSrc;
6680
} else {
6781
// This is for IE 8 and below.
68-
script.text = src;
82+
script.text = trustedSrc;
6983
}
7084
parent.appendChild(script);
7185
// Don't pollute the DOM with hundreds of <script> tags.

0 commit comments

Comments
 (0)