Hi. I’ve been following some MDN examples to write a simple addon to add an extra context menu option to open links without passing the referer. The addon copies a link and opens a new tab to the selected link.
It mostly works, but I’ve noticed some servers give 404 errors when a plain “&” ampersand symbol is replaced by “& amp;”. Some sites resolve to the correct page, but others don’t see “& amp;” as equivalent to & in the URL. (Space added between “&” and “amp;” only because the forum or browser is replacing the escaped character code “&”.)
The code below borrowed from the MDN examples uses the escapeHTML function to replace potential XSS characters. I’m not sure how to approach this. Even if I split the parameters and concatenate them back together with plain “&” symbols in-between, it seems like that would still open up the potential for unwanted special character codes in the reassembled query string.
What’s the best way to handle sanitizing a link, when it seems like many sites will not resolve pages with “& amp;” substitutions in the URL? Is this escaping even necessary in this case of opening a selected link in a new tab?
Does the linkUrl property of menus.OnClickData already have XSS protection built-in? How does the built-in context menu handle sanitizing the links selected for the default “Open Link in New Tab” without breaking links?
browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "open-link-in-new-tab") {
// Always HTML-escape external input to avoid XSS.
const safeUrl = escapeHTML(info.linkUrl);
browser.tabs.create({url: safeUrl, active: false});
// https://gist.github.com/Rob--W/ec23b9d6db9e56b7e4563f1544e0d546
function escapeHTML(str) {
return String(str)
.replace(/&/g, "&")
.replace(/"/g, """).replace(/'/g, "'")
.replace(/</g, "<").replace(/>/g, ">");