How to fix this error in chrome extension v3?
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
if (isPdfDownloadable(details)) {
return undefined;
}
var viewerUrl = getViewerURL(details.url);
return { redirectUrl: viewerUrl };
},
{
urls: [
"file://*/*.pdf",
"file://*/*.PDF",
...// Duck-typing: MediaError.prototype.message was added in Chrome 59.
(MediaError.prototype.hasOwnProperty("message")
? []
: [
// Note: Chrome 59 has disabled ftp resource loading by default:
// https://www.chromestatus.com/feature/5709390967472128
"ftp://*/*.pdf",
"ftp://*/*.PDF",
]),
],
types: ["main_frame", "sub_frame"],
},
["blocking"]
);
Just tried to block, but not working. Who has any experiences to solve this?
Related
I am trying to write an extension in Manifest Version 3, where I want to modify cookie headers for certain requests. Since the rule will only be applied to specific requests that meets my conditions,
I thought of adding a dynamic rule temporarily for that request, modify the cookie header, and immediately remove it. Here's the function for that rule.
if (condition) {
function makeNewRule(url) {
chrome.declarativeNetRequest.updateDynamicRules(
{
addRules:
[
{
"id": 1000,
"priority": 100,
"action": {
"type": "modifyHeaders",
"requestHeaders": [
{
"header": "cookie",
"operation": "set",
"value": "Modified cookie value 1"
}
]
},
"condition": {
"urlFilter" : url,
"resourceTypes":
["csp_report", "font", "image",
"main_frame", "media", "object",
"other", "ping", "script",
"stylesheet", "sub_frame",
"webbundle", "websocket",
"webtransport"]
}
}
],
removeRuleIds: [1000],
});
}
}
While this works for all requests that meet my condition, and the cookies are being modified observed in the chrome developers tool network window, the rule persists for a later session, even if I reload/update the unpacked extension. If I change the value of the cookie header to ""Modified cookie value 2", the developers tools still shows the previous "Modified cookie value 1". Therefore, I am assuming that the rule that I added is not being removed, and it is persisting across browser sessions. I tried cleaning the cache and reloading the browser. Additionally,
chrome.declarativeNetRequest.getDynamicRules(
e => console.log(e)
);
The snippet above shows the existence of the rule even when removed. How do I remove the rule that I added dynamically within that session?
I update my dynamic rules by removing and then adding them, I'll share my code with you, I hope it helps.
To update rules
function UpdateIntercept(token: string) {
chrome.declarativeNetRequest.updateDynamicRules({
removeRuleIds: GetInterceptRules(token).map((rule) => rule.id), // remove existing rules
addRules: GetInterceptRules(token)
});
chrome.declarativeNetRequest.getDynamicRules(
e => console.log(e)
);
}
then when I intercept the url
function GetInterceptRules(token: string) {
const allResourceTypes =
Object.values(chrome.declarativeNetRequest.ResourceType);
return [
{
id: 1,
priority: 1,
action: {
type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
requestHeaders: [
{
operation: chrome.declarativeNetRequest.HeaderOperation.SET,
header: 'Authorization',
value: 'Bearer ' + token,
},
]
},
condition: {
urlFilter: liveApiUrl,
initiatorDomains: ["mail.google.com"],
resourceTypes: allResourceTypes,
}
},
{
id: 2,
priority: 1,
action: {
type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
requestHeaders: [
{
operation: chrome.declarativeNetRequest.HeaderOperation.SET,
header: 'Authorization',
value: 'Bearer ' + token,
},
]
},
condition: {
urlFilter: testApiUrl,
initiatorDomains: ["mail.google.com"],
resourceTypes: allResourceTypes,
}
}
];
}
To intercept the url you want
function interceptURL(requestDetails: chrome.webRequest.WebRequestBodyDetails) {
console.log('intercepted: ' + requestDetails.url);
if (requestDetails.url.includes(liveApiUrl) || requestDetails.url.includes(testApiUrl)) { //maybe the inclue
chrome.runtime.sendMessage({ "message": "refresh_token" }, (token: string) => {
console.log('refreshed token: ' + token)
if (token == undefined) {
chrome.runtime.sendMessage({ "message": "get_token" });
}
});
}
}
I use onBeforeRequest
chrome.webRequest.onBeforeRequest.addListener(
interceptURL,
{ urls: [liveApiUrl, testApiUrl] }
)
In my case, I need to pass a refresh token everytime I intercept that url
still have a couple of things to work on, but hopefully it gives you some direction.
I have issue with chrome extension in manifest v3. Usually reproduce on MacOS. Before migrating to manifest v3 my app was on manifest v2 and I did't have this problems. Some times app is
not reacting on click at icon of list extensions. So I need to reload computer or disabled the app and after turn on it to resolve this problem. In console i have errors: "Could not establish connection. Receiving end does not exist.", "ResizeObserver loop limit exceeded", "Request failed with status code 403". Or without any errors in console. It seems like service worker don't start again or stuck in the loop
"background": {
"service_worker": "js/background.js",
"type": "module"
},
"content_scripts": [{
"matches": ["<all_urls>"],
"js": [
"js/contentscript.js"
]
}],
this is code from manifest
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => Promise.resolve()
.then(() => { sendResponse(); })
.then(() => {
if (message === 'toggle-popup') {
updateApplicationTab((idTab) => {
chrome.tabs.sendMessage(idTab, { message: 'clicked_browser_action' });
});
}
if (message === 'toggle-popup_set_id') {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.runtime.sendMessage({
type: 'setActiveTab',
data: tabs[0].id,
});
});
}
}),
);
this is code from worker to open app
want an example chrome.webRequest.onBeforeSendHeaders.addListener() in [manifest_version:3],to change requestHeaders
chrome.webRequest.onBeforeSendHeaders.addListener(
(details) => {
return { requestHeaders: details.requestHeaders };
},
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders", "extraHeaders"]);
When I try to convert an XML file (requested from an external server) to JSON, it seems to me that xml2json does convert it however, not to a correct JSON file. Is there something that needs to be adjusted. I seem to be missing quotes for the keys.
This is my current code
app.get('/api/convertabstract/:id', async (req, res, next) => {
var data = '';
var finaldata = '';
function vertaaldata(){
return new Promise (resolve => {
https.get('https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=' + ' 11748933,11700088' +'&retmode=xml', function(res) {
if (res.statusCode >= 200 && res.statusCode < 400) {
res.on('data', function(data_) { data += data_.toString(); });
res.on('end', function() {
parser.parseString(data, function(err, result) {
finaldata = util.inspect(result, false, null, true);
}), resolve('klaar');
});
}})})
}
async function calltranslator() {
const result = await vertaaldata();
console.log(finaldata.PubmedArticleSet);
res.send('dit is de data:' + finaldata)
}
calltranslator();
});
JSON output:
{ PubmedArticleSet: {
PubmedArticle: [
{
MedlineCitation: [
{
[32m'$'[39m: { Status: [32m'MEDLINE'[39m, Owner: [32m'NLM'[39m },
PMID: [ { _: [32m'11748933'[39m, [32m'$'[39m: { Version: [32m'1'[39m } } ],
DateCompleted: [ { Year: [ [32m'2002'[39m ], Month: [ [32m'03'[39m ], Day: [ [32m'04'[39m ] } ],
DateRevised: [ { Year: [ [32m'2006'[39m ], Month: [ [32m'11'[39m ], Day: [ [32m'15'[39m ] } ],
Article: [
{
[32m'$'[39m: { PubModel: [32m'Print'[39m },
Journal: [
{
ISSN: [ { _: [32m'0011-2240'[39m, [32m'$'[39m: { IssnType: [32m'Print'[39m } } ],
JournalIssue: [....etc....
As far as I can tell, xml2js and xml2json are completely unrelated libraries. Which are you actually using - you mention both! xml2js doesn't claim to generate JSON, it claims to generate Javascript.
I'm trying to reproduce this example with the manifest v3. But my action is always active - I expext it to be disabled on all pages without 'g' in a URL.
Thanks in advance!
manifest.json
{
"name":"Example",
"description":"description",
"version":"0.1",
"manifest_version":3,
"background":{
"service_worker":"background.js"
},
"permissions":[
"declarativeContent"
],
"action":{
"default_icon":{
"16":"/images/get_started16.png",
"32":"/images/get_started32.png",
"48":"/images/get_started48.png",
"128":"/images/get_started128.png"
},
"default_title":"press here to open"
},
"icons":{
"16":"/images/get_started16.png",
"32":"/images/get_started32.png",
"48":"/images/get_started48.png",
"128":"/images/get_started128.png"
}
}
background.js
chrome.runtime.onInstalled.addListener(() => {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL contains a 'g' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'g' },
})
],
// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
], function callback(details) {
console.log("chrome.declarativeContent.onPageChanged.addRules callback");
console.log(details);
});
});
});
as wOxxOm mentioned
this answer helped.