Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,88 @@ browser.webRequest.onBeforeRequest.addListener(
);
```

This example shows, how to handle a non-UTF-8 page:

```js
Object.defineProperty(Array.prototype, "indexOfMulti", {
value: function (searchElements, fromIndex) {
let i = this.indexOf(searchElements[0], fromIndex);
if (searchElements.length === 1 || i === -1) {
// Not found or no other elements to check
return i;
}

const initial = i;
for (
let j = 1, m = searchElements.length, n = this.length;
j < m && i < n;
j++
) {
if (this[++i] !== searchElements[j]) {
return this.indexOfMulti(searchElements, initial + 1);
}
}

return i === initial + searchElements.length - 1 ? initial : -1;
},
});

const encoder = new TextEncoder();
const start1 = encoder.encode(
'<a href="/pc/" class="p-catList_cell p-catList_cell--pc-">',
);
const end1 = encoder.encode("</a>");
const start2 = encoder.encode('<li class="p-catList_items_item">');
const end2 = encoder.encode("</li>");

const words = [
"laptop",
"tablet",
"hard disk",
"PC parts",
"Peripheral equipment",
].map((word) => encoder.encode(word));

function listener(details) {
const filter = browser.webRequest.filterResponseData(details.requestId);

const data = [];
filter.ondata = (event) => {
const buffer = new Uint8Array(event.data);
for (let i = 0, l = buffer.length; i < l; i++) {
data.push(buffer[i]);
}
};

filter.onstop = (event) => {
let start = data.indexOfMulti(start1);
if (start != -1) {
let end = data.indexOfMulti(end1, start + start1.length);
let parent = data.splice(start, end - start + end1.length);
let pos = 0;
for (const word of words) {
let start = parent.indexOfMulti(start2, pos);
let end = parent.indexOfMulti(end2, start + start2.length);
let text = parent.slice(start + start2.length, end);
// Replace original text with our text
parent.splice(start + start2.length, text.length, ...word);
pos = end;
}
// Insert modified array
data.splice(start, 0, ...parent);
}
filter.write(new Uint8Array(data));
filter.close();
};
}

browser.webRequest.onBeforeRequest.addListener(
listener,
{ urls: ["https://kakaku.com/"], types: ["main_frame"] },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason not to use https://example.com/?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The page has utf-8 encoding.

["blocking"],
);
```

{{WebExtExamples}}

## Browser compatibility
Expand Down