I'm trying to modify the referer-policy header with my Chrome extension, but it doesn't affect the response headers.
Manifest.json:
{
"name": "My Example Extension",
"version": "1.0",
"description": "",
"permissions": [
"webRequest",
"webRequestBlocking",
"*://*/*"
],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"manifest_version": 2
}
background.js:
chrome.webRequest.onHeadersReceived.addListener(details => {
let header = details.responseHeaders.find(e => e.name.toLowerCase() === 'referrer-policy');
// Check if the header has been defined already
if (typeof header !== 'undefined') {
console.log ('Modifying header');
header.value = 'strict-origin';
}
else {
details.responseHeaders.push({ name: 'referrer-policy', value: 'strict-origin' });
}
return {responseHeaders: details.responseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);
I added debug outputs which show that the code modifies or adds the header accordingly but there is no effect in the browser itself.
I was writing exactly the same code when trying to modify response headers in extension.
// manifest.json
"permissions": [
"webRequest", "webRequestBlocking", "https://developer.chrome.com/*"
]
// background.js
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
const newHeader = {name:"foo", value:"bar"};
const responseHeaders = details.responseHeaders.concat(newHeader);
return { responseHeaders };
},
// filters
{
urls: ["https://developer.chrome.com/*"],
},
// extraInfoSpec
["blocking","responseHeaders"]
);
It just doesn't work at all.
Until I've changed the last argument to:
// extraInfoSpec
["blocking","responseHeaders", "extraHeaders"]
It finally works.
By revisiting the document, in the last paragraphs of Life cycle of requests section:
Starting from Chrome 79, ... On the other hand, response header modifications do not work to deceive CORS checks. If you need to deceive the CORS protocol, you also need to specify 'extraHeaders' for the response modifications.
You were not returning the modified headers. Try with:
chrome.webRequest.onHeadersReceived.addListener(details => {
let myResponseHeaders = details.responseHeaders;
let header = myResponseHeaders.find(e => e.name == 'Referrer-Policy');
// Check if the header has been defined already
if (header) {
console.log ('Modifying header');
let headerIndex = myResponseHeaders.indexOf(header);
myResponseHeaders.splice(headerIndex,1);
}
myResponseHeaders.push({ name: 'Referrer-Policy', value: 'strict-origin' });
return {responseHeaders: myResponseHeaders};
}, {urls: ["*://*/*"]}, ['blocking', 'responseHeaders']);
Or with a slightly modified code copied from the documentation:
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
for (var i = 0; i < details.responseHeaders.length; ++i) {
if (details.responseHeaders[i].name === 'Referrer-Policy') {
details.responseHeaders[i].value = 'strict-origin';
break;
}
}
return {responseHeaders: details.responseHeaders};
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]);
Related
I have a REST script that's currently working well for single-record PUT requests. I'm looking to update the script such that it can support multi-record updates.
Current Script:
function put(context) {
// doValidation([context.recordtype, context.id], ['recordtype', 'id'], 'PUT');
var rec = record.load({
type: context.recordtype,
id: context.id
});
var values = context.values;
for (var fldName in values) {
if (values.hasOwnProperty(fldName)) {
rec.setValue({
fieldId: fldName,
value: values[fldName]
});
}
}
rec.save({
ignoreMandatoryFields: true
});
rec = record.load({
type: context.recordtype,
id: context.id
});
return rec; // reloading includes the results of any triggered actions.
}
return {
post: postProcess,
put: put
};
Working Single Record JSON body payload for PUT request:
{
"recordtype": "customrecord_record",
"id": "201",
"values": {
"custrecord_managementpriority": "3"
}
Ideally looking for the PUT script to support this payload structure:
{
"recordtype": "customrecord_record",
"id": "201",
"values": {
"custrecord_managementpriority": "3"
}
},
{
"recordtype": "customrecord_record",
"id": "204",
"values": {
"custrecord_managementpriority": "4"
}
}
(Wrapped in [ ] or however necessary of course).
Solved. Will leave this post up in case anyone else runs into this issue. This piece upfront did the trick:
var contexts = context;
if(!Array.isArray(contexts))
contexts = [contexts];
var rec;
contexts.forEach((context) => {
I am trying to develop a chrome extension and in this extension, I need the target related events (targetCreated/targetInfoChanged/targetDestroyed).
To achieve that goal I am using setDiscoverTargets method from the devtools protocol by means of chrome.debugger API. Here is the pseudocode that I am using:
// attach the debugger
chrome.debugger.attach(debuggeeId, version, onAttach);
// when attach is successful send setAuthAttach to make setDiscoverTargets command work
const onAttach = (debuggeeId) => {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
console.log(`onAttach: ${JSON.stringify(debuggeeId)}`);
chrome.debugger.sendCommand({ tabId: myTabId }, "Target.setAutoAttach", { autoAttach: false, waitForDebuggerOnStart: false, flatten: true }, setAutoAttachHandler);
}
// when auto attach handler is successful send setDiscoverTargets method
// to enable targetCreated/targetInfoChanged/targetDestroyed events
const setAutoAttachHandler = (result) => {
if (chrome.runtime.lastError) {
console.log("error in setAutoAttachHandler:" + chrome.runtime.lastError.message);
return;
}
console.log(`setAutoAttachHandler result: ${JSON.stringify(result)}`);
chrome.debugger.sendCommand({ tabId: myTabId }, 'Target.setDiscoverTargets', { discover: true }, setDiscoverTargetsHandler);
}
// see the result of command
const setDiscoverTargetsHandler = (result) => {
if (chrome.runtime.lastError) {
console.log("error in setDiscoverTargetsHandler:" + chrome.runtime.lastError.message);
return;
}
console.log(`setDiscoverTargets result: ${JSON.stringify(result)}`);
}
As per execute the code above I am always getting not allowed error
error in setDiscoverTargetsHandler:{"code":-32000,"message":"Not
allowed"}
And the events related to the target are not fired. Is there anything else I should do to get those events?
thank you.
Methods under Target and Browser domain(except for Browser.getVersion) are not allowed when sending command from chrome.debugger api. But if you want to observe for tabs to which debugger is attached or tabs in which developer tools is opened then you can poll chrome.debugger.getTargets at regular intervals. You will get response, something like this :-
[{
"attached": true,
"faviconUrl": "https://www.wikipedia.org/static/favicon/wikipedia.ico",
"id": "DEA9ED6A4A3DFB9A6FC315AF7110465B",
"tabId": 88,
"title": "Wikipedia",
"type": "page",
"url": "https://www.wikipedia.org/,
}, {
"attached": false,
"faviconUrl": "https://github.githubassets.com/favicons/favicon.svg",
"id": "3314432045C3EC141D4C7D7023606122",
"tabId": 87,
"title": "GitHub",
"type": "page",
"url": "https://github.com/"
}]
I have a chrome extension that I'm developing. Using process monitor, I'm filtering on NativeMessagingHosts in the path and it never gets hit on the registry. Here is my REG file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\Google\Chrome\NativeMessagingHosts\com.app.native.messaging.ChromeMessageRepeater]
#="C:\\Prototypes\\Plugins\\DG2\\com.app.native.messaging.ChromeMessageRepeater.json"
Now, here is the JSON for the plugin manifest:
{
"manifest_version": 2,
"name": "--------- 2.0",
"description": "",
"version": "2.0",
"content_scripts" :[
{
"matches": ["*://*/*"],
"run_at": "document_idle",
"js": ["jquery-1.12.2.min.js", "dg2.js"]
}
],
"background": {
"page": "back.html",
"persistent": true
},
"permissions": [ "nativeMessaging", "alarms", "tabs", "activeTab", "*://*/*"]
}
here is the json for the native messaging app
{
"name": "com.app.native.messaging.ChromeMessageRepeater",
"description": "",
"path": "ChromeMessageRepeater.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://lpldkcbggjamnjbndpddgoikgeabfapb/"
],
"permissions": [
"nativeMessaging"
]
}
Any idea why the registry key is never read? When trying to use the plugin, the Port is never opened if I use chrome.runtime.connectNative nor if I used chrome.runtime.sendNativeMessage
EDIT:
function postMessage2(url, dom) {
var port = chrome.runtime.connectNative("com.app.native.messaging.ChromeMessageRepeater");
if(typeof chrome.runtime.lastError !== 'undefined') console.log(chrome.runtime.lastError.message);
port.onMessage.addListener(function(msg) {
console.log("Received" + msg);
});
port.onDisconnect.addListener(function() {
console.log("Disconnected");
});
try {
port.postMessage({ text: url + ';' + dom });
}
catch(ex) {
console.error(ex);
}
};
function postMessage(url, dom) {
chrome.runtime.sendNativeMessage("com.app.native.messaging.ChromeMessageRepeater", { text: url + ';' + dom });
if(typeof chrome.runtime.lastError !== 'undefined') {
console.log(chrome.runtime.lastError.message);
}
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.type === "native"){
postMessage2(request.url, request.dom);
sendResponse({ result: true });
}
}
);
I would like to display all of my recent commit messages from github on a website. Is this possible?
To get the public events of a user, you should use the /users/:user/events endpoint (Events performed by a user):
curl https://api.github.com/users/IonicaBizau/events
This will give you back a JSON response like this:
[
{
"type": "IssueCommentEvent",
...
}
{
"id": "3349705833",
"type": "PushEvent",
"actor": {...},
"repo": {...},
"payload": {
"push_id": 868451162,
"size": 13,
"distinct_size": 1,
"ref": "refs/heads/master",
"head": "0ea1...12162",
"before": "548...d4bd",
"commits": [
{
"sha": "539...0892e",
"author": {...},
"message": "Some message",
"distinct": false,
"url": "https://api.github.com/repos/owner/repo/commits/53.....92e"
},
...
]
},
"public": true,
"created_at": "2015-11-17T11:05:04Z",
"org": {...}
},
...
]
Now, you only need to filter the response to include only the PushEvent items.
Since you want to display these events on a website, probably you want to code it in javascript. Here is an example how to do it using gh.js–an isomorphic GitHub API wrapper for JavaScript/Node.js written by me:
// Include gh.js
const GitHub = require("gh.js");
// Create the GitHub instance
var gh = new GitHub();
// Get my public events
gh.get("users/IonicaBizau/events", (err, res) => {
if (err) { return console.error(err); }
// Filter by PushEvent type
var pushEvents = res.filter(c => {
return c.type === "PushEvent";
});
// Show the date and the repo name
console.log(pushEvents.map(c => {
return "Pushed at " + c.created_at + " in " + c.repo.name;
}).join("\n"));
// => Pushed at 2015-11-17T11:05:04Z in jillix/jQuery-json-editor
// => Pushed at 2015-11-16T18:56:05Z in IonicaBizau/html-css-examples
// => Pushed at 2015-11-16T16:36:37Z in jillix/node-cb-buffer
// => Pushed at 2015-11-16T16:35:57Z in jillix/node-cb-buffer
// => Pushed at 2015-11-16T16:34:58Z in jillix/node-cb-buffer
// => Pushed at 2015-11-16T13:39:33Z in IonicaBizau/ghosty
});
I have an extension to count the number of stylesheets.
When the icon is pressed, the stylesheets of all opened windows or tabs are shown.
However, the extension has no effect on the windows and tabs that are opened later.
How can I solve it ?
manifest.json
{
"name": "StyleSheets counter",
"description": "It counts the stylesheets linked with the web page",
"version": "2.0",
"permissions": [
"tabs",
"*://*/*",
"activeTab",
"debugger"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_icon": "SS Counter"
},
"icons": {
"48": "on.png",
"48": "off.png"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
executeScriptsInExistingTabs();
});
function executeScriptsInExistingTabs(){
chrome.windows.getAll(null, function(wins) {
for (var j = 0; j < wins.length; ++j) {
chrome.tabs.getAllInWindow(wins[j].id, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
if (tabs[i].url.indexOf("chrome://") != 0) {
chrome.tabs.executeScript(tabs[i].id, { file: 'counter_ss.js' });
}
}
});
}
});
}
counter_ss.js
var theSheets = document.styleSheets;
alert("Number of stylesheets: " + theSheets.length);
Add onClicked event listener with your function executeScriptsInExistingTabs as callback.
I have already the solution, for the new tabs and for the ones whose URL is changed:
chrome.tabs.onCreated.addListener(function(tab) {
//none is done here
});
chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
if (info.status == "complete") {
chrome.tabs.executeScript(tabid, {file:'counter_ss.js'});
}
});
The code inside
chrome.tabs.onUpdated.addListener
is run both, when the new tabs are open and when the URL of a tab is changed. So to avoid duplication, none is done in the
chrome.tabs.onCreated.addListener
However, it must be there (altough empty).