In manifest v3 is conditional redirecting possible? - google-chrome-extension

We have a Chrome extension that we use that allows our developers to quickly setup redirects for certain URLs, for easier debugging across different clients' sites. It currently uses manifest v2 manifest with webRequestBlocking.
In brief, it behaves something like this:
Search for a URL pattern like: https://www.example.com/c1234/path/to/javascript.js
Use the c1234 part of the matched URL in an HTTP call to a web service that to look-up the value of a variable, which we'll call shortName here.
Redirect the URL in #1 to a new URL that follows a pattern something like this: https://localhost/imp-{shortName}/javascript.js.
With the declarativeNetRequest in manifest v3, I'm able to set rules that redirect using regular expressions, but I don't see any way to use a part of the matched URL to look-up a variable from an outside source (step #2) above.
Is this not possible with manfiest v3 at all? I'm using the updateSessionRules API as follows:
chrome.declarativeNetRequest.updateSessionRules({
addRules: [
{
id: 1,
action: {
type: 'redirect',
redirect: {
regexSubstitution: '\1://localhost/{shortName}/javascript.js'
}
},
condition: {
regexFilter: '^(https?):.+(example.com).+(c[0-9]+).+javascript.+$'
}
}
];
rules,
removeRuleIds: [1]
});
In manifest v2, I used chrome.webRequest.onBeforeRequest to intercept before the request was made:
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return redirectOnMatch(details);
},
{
urls : ["<all_urls>"]
},
["blocking"]
);
The redirectOnMatch function would first check to see if the URL matched a pattern, and if it did, extract the c1234 value and use it in an HTTP call.
Is there any way to have code run and set the redirect rules before the request is made in manifest v3?

Related

Is it possible to match ccTTL domains to webRequest listener?

I am trying to make firefox addon redirects connection to another link, translating ccTLD domain name to gTLD one.
(http://foo.bar.co.baz/GETdata)->(http://foo.qux.com/GETdata)
I tried match pattern and other options, without any luck.
Match pattern (https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns)
: It seems like parser does not support ccTLD(ex: foo.co.au), but only gTLD (ex: foo.com).
events.UrlFilter (https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/events/UrlFilter)
: It seems it's not for webRequest.
<all_urls>
: I also tried to call listener for all domains, then filter it inside the listener by if(details.url.contains("domain-name")) statement, which failed. It did managed to filter other gTLD domains, but not ccTLD ones.
var pattern = "https://mdn.mozillademos.org/*";
function redirect(requestDetails) {
console.log("Redirecting: " + requestDetails.url);
return {
redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
};
}
browser.webRequest.onBeforeRequest.addListener(
redirect,
{urls:[pattern], types:["image"]},
["blocking"]
);
//used MDN example code. permission is given to entire hosts in manifest.json
I can't get ccTLD filtered with any options.
It seems internal parser simply can't handle it since 3rd option also failed.
Am I missing something?

How to redirect to ASP.NET Ideneity login page?

Using ASP.NET Identity, if I want to construct an <a> element that links to the Login page I can use Razor Helpers and some magic strings:
<a asp-area="Identity" asp-page="/Account/Login">Login</a>
(Not the question at hand, but I'd be happy if someone would tell me why this convoluted collection of magic strings is somehow better than hardcoding the "/Identity/Account/Login" relative URL.)
My question is: If I want to return a redirect from a Handler routine (i.e., the C# code behind a razor page), is there some recommended magic that I should be using to get a relative URL to the Login page?
In other words, is there something better than:
return Redirect("/Identity/Account/Login");
Use it this way:
return RedirectToPage("/Account/Login", new { area = "Identity" });
You may be missing RazorPages. Depending on how your mapping occurs in your program.cs, either add in your Web.config
services.AddRazorPages;
or in your .Net6 Programs.cs use
builder.Services.AddRazorPages;
or if you are using endpoints, replace
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
with
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});

How do I generate sitemap for dynamic links in expressjs?

I have a jobpage which has url as /jobpage/:categoryname/:companyname/:jobtitle/:jobid. Parameters are generated dynamically. I want all such dynamically generated links on sitemap. I have used express-sitemap package, code is as below -
var sitemap = require('express-sitemap');
sitemap({
sitemap: 'sitemap.xml', // path for .XMLtoFile
robots: 'robots.txt', // path for .TXTtoFile
generate: app, // option or function, is the same
sitemapSubmission: '/sitemap.xml', // path of sitemap into robots
url : 'xxxx',
map: {
'/jobpage': ['get'],
'/college': ['get'],
},
route: { // specific option for some route
'/jobpage': {
lastmod: '2016-04-25',
changefreq: 'weekly',
priority: 1.0,
},
},
}).toFile(); // write sitemap.xml and robots.txt
Sitemap is getting generated with link as
<url>
<loc>xxxx/jobpage/:categoryname/:companyname/:jobtitle/:jobid</loc>
</url>
How do I generate dynamic links? Any leads will be highly appreciated.
in my case i did it like below.
Create a separate file that sitemap_generator.js which actually read all database models which leads to pages.
then generate xml and write to web folder and in certain interval it keep updating xml as well.
it start creating sitemap when node server start. i did this manually because i found no automated solution comes with limitations.
i think most of time your business logic might not fit into any lib, because that libs can't know what dynamic pages can be. which you already knew.
https://www.npmjs.com/package/express-sitemap

How to ignore route with New Relic for NodeJS

I have a nodejs app which has the new relic module installed.
Everything is set up but I don't know how to exclude a route from the new relic tracker.
I have this script at http://www.website.com/match/findMatch which usually takes at least 4 seconds and I want to add it to the exclusion list.
The rest of the scripts usually take 0.1s but this one makes my ApDex give out alerts which aren't correct.
I already have this in my conf file because I use websockets:
rules : {
ignore : [
'^\/socket\.io\/.*\/xhr-polling',
'^\/socket\.io\/.*\/websocket',
]
}
I've read the docs here 3 times but still don't understand how to do it.
You'll want to add a new ignore rule that matches requests to http://www.website.com/match/findMatch.
Rules can be strings or regular expressions (like the socket.io examples). If the request you want to ignore is always http://www.website.com/match/findMatch (not, for example, http://www.website.com/match/findMatch?q=foo, you can do this:
rules : {
ignore : [
'^\/socket\.io\/.*\/xhr-polling',
'^\/socket\.io\/.*\/websocket',
'http://www.website.com/match/findMatch'
]
}

How to use the experimental offscreenTab API?

I've been searching for examples and reference and have come up with nothing. I found a note in offscreenTab source code mentioning it cannot be instantiated from a background page (it doesn't have a tab for the offscreenTab to relate to). Elsewhere I found mention that popup also has no tie to a tab.
How do you successfully create an offscreenTab in a Chrome extension?
According to the documentation, offscreenTabs.create won't function in a background page. Although not explicitly mentioned, the API cannot be used in a Content script either. Through a simple test, it seems that the popup has the same limitation as a background page.
The only leftover option is a tab which runs in the context of a Chrome extension. The easiest way to do that is by using the following code in the background/popup:
chrome.tabs.create({url: chrome.extension.getURL('ost.htm'), active:false});
// active:false, so that the window do not jump to the front
ost.htm is a helper page, which creates the tab:
chrome.experimental.offscreenTabs.create({url: '...'}, function(offscreenTab) {
// Do something with offscreenTab.id !
});
To change the URL, use chrome.experimental.offscreenTabs.update.
offscreenTab.id is a tabId, which ought to be used with the chrome.tabs API. However, at least in Chrome 20.0.1130.1, this is not the case. All methods of the tabs API do not recognise the returned tabID.
A work-around is to inject a content script using a manifest file, eg:
{"content_scripts": {"js":["contentscript.js"], "matches":["<all_urls>"]}}
// contentscript.js:
chrome.extension.sendMessage({ .. any request .. }, function(response) {
// Do something with response.
});
Appendum to the background page:
chrome.extension.onMessage.addListener(function(message, sender, sendResponse) {
// Instead of checking for index == -1, you can also see if the ID matches
// the ID of a previously created offscreenTab
if (sender.tab && sender.tab.index === -1) {
// index is negative if the tab is invisible
// ... do something (logic) ...
sendResponse( /* .. some response .. */ );
}
});
With content scripts, you've got full access to a page's DOM. But not to the global object. You'll have to inject scripts (see this answer) if you want to run code in the context of the page.
Another API which might be useful is the chrome.webRequest API. It can be used to modify headers/abort/redirect requests. Note: It cannot be used to read or modify the response.
Currently, the offscreenTabs API is experimental. To play with it, you have to enable the experimental APIs via chrome://flags, and add "permissions":["experimental"] to your manifest file. Once it's not experimental any more, use "permissions":["offscreenTabs"].

Resources