Skip to content

Commit

Permalink
fix closure bug for trusted-replace-xhr-response
Browse files Browse the repository at this point in the history
  • Loading branch information
stanislav-atr committed Dec 16, 2022
1 parent 4f1d59b commit 492da8f
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
17 changes: 9 additions & 8 deletions src/scriptlets/trusted-replace-xhr-response.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ export function trustedReplaceXhrResponse(source, pattern = '', replacement = ''
const nativeOpen = window.XMLHttpRequest.prototype.open;
const nativeSend = window.XMLHttpRequest.prototype.send;

let shouldReplace = false;
let xhrData;
let requestHeaders = [];

const openWrapper = (target, thisArg, args) => {
// eslint-disable-next-line prefer-spread
Expand All @@ -106,13 +104,16 @@ export function trustedReplaceXhrResponse(source, pattern = '', replacement = ''
return Reflect.apply(target, thisArg, args);
}

shouldReplace = matchRequestProps(source, propsToMatch, xhrData);
if (matchRequestProps(source, propsToMatch, xhrData)) {
thisArg.shouldBePrevented = true;
}

// Trap setRequestHeader of target xhr object to mimic request headers later
if (shouldReplace) {
if (thisArg.shouldBePrevented) {
thisArg.collectedHeaders = [];
const setRequestHeaderWrapper = (target, thisArg, args) => {
// Collect headers
requestHeaders.push(args);
thisArg.collectedHeaders.push(args);
return Reflect.apply(target, thisArg, args);
};

Expand All @@ -129,7 +130,7 @@ export function trustedReplaceXhrResponse(source, pattern = '', replacement = ''
};

const sendWrapper = (target, thisArg, args) => {
if (!shouldReplace) {
if (!thisArg.shouldBePrevented) {
return Reflect.apply(target, thisArg, args);
}

Expand Down Expand Up @@ -197,13 +198,13 @@ export function trustedReplaceXhrResponse(source, pattern = '', replacement = ''

// Mimic request headers before sending
// setRequestHeader can only be called on open request objects
requestHeaders.forEach((header) => {
thisArg.collectedHeaders.forEach((header) => {
const name = header[0];
const value = header[1];

forgedRequest.setRequestHeader(name, value);
});
requestHeaders = [];
thisArg.collectedHeaders = [];

try {
nativeSend.call(forgedRequest, args);
Expand Down
1 change: 0 additions & 1 deletion tests/scriptlets/prevent-xhr.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -608,7 +608,6 @@ if (isSupported) {
xhr2.open(METHOD, URL_TO_BLOCK);

xhr1.onload = () => {
clearGlobalProps('hit');
assert.strictEqual(xhr1.readyState, 4, 'Response done');
assert.ok(xhr1.response, 'Response data exists');
assert.strictEqual(window.hit, undefined, 'hit should not fire');
Expand Down

0 comments on commit 492da8f

Please sign in to comment.