Chrome extension not storing value to chrome.storage.local? - javascript

I'm trying to build an extension to monitor the xhr portion of the devtools network tab. With some help , I have been able to get the requests to be displayed on the service-worker console and I can log the Post requests. My next step is to send some data to chrome.storage.local, so it can be read later by a content script. However although I am getting
console.log(point);
outputted in the service worker console, I am not seeing any output in either console containing:
console.log('Value is set to ' + point)
No errors seen though. What am I doing wrong?
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": ["*://*.cnn.com/", "],
"permissions": ["webRequest", "activeTab","tabs"],
"content_scripts": [
{
"matches": ["*://cnn.com/*"],
"js": ["contentScript.js"]
}
]
}
In my background.js:
(function () {
var point;
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
point = body.CenterPoint.Point;
console.log(point);
},
{ urls: [url] },
["requestBody"]
);
chrome.storage.local.set({ 'key': point }, function () {
console.log('Value is set to ' + point);
});
})();

Based on comments I have the following working code:
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
point = body.CenterPoint.Point;
console.log(point);
chrome.storage.local.set({ 'key': point }, function () {
console.log('Value is set to ' + point);
});
},
{ urls: [url] },
["requestBody"]
);

Related

Chrome extension: Content script not picking up changes to chrome.storage

I'm trying to build an extension to monitor the xhr portion of the devtools network tab. With some help , I have been able to get the requests to be displayed on the service-worker console and I can log the Post requests. I'm also now saving the data "point" in chrome.storage. My next step is to read the data from chrome.storage.local, and have the content script log it to the console. However although I am getting no errors, I don't see any output in the console. No errors seen though. What am I doing wrong?
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": ["*://*.cnn.com/"],
"permissions": ["webRequest", "activeTab","tabs"],
"content_scripts": [
{
"matches": ["*://cnn.com/*"],
"js": ["popup.js"]
}
]
}
In my background.js:
(function () {
var point;
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
point = body.CenterPoint.Point;
console.log(point);
chrome.storage.local.set({ 'key': point }, function () {
console.log('Value is set to ' + point);
});
},
{ urls: [url] },
["requestBody"]
);
})();
popup.js:
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${namespace}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`
);
}
});

Chrome extension: Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist

I'm trying to build an extension to monitor the xhr portion of the devtools network tab. With some help , I have been able to get the requests to be displayed on the service-worker console and I can log the Post requests. My next step is to send some post info to the extension popup. However I am getting:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
manifest.json:
{
"manifest_version": 3,
"version": "1.0",
"name": "Hello World!",
"description": "Learning how to make a chrome extension!",
"icons": {
"16": "images/puppy16.png",
"48": "images/puppy48.png",
"128": "images/puppy128.png"
},
"action": {
"default_icon": "images/puppy.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "background.js"
},
"host_permissions": ["*://*.cnn.com/", "],
"permissions": ["webRequest", "activeTab","tabs"],
"content_scripts": [
{
"matches": ["*://cnn.com/*"],
"js": ["contentScript.js"]
}
]
}
In my background.js:
(function () {
var tab
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
tab = tabs[0];
console.log(tab);
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
// Use this to decode the body of your post
const postedString = decodeURIComponent(String.fromCharCode.apply(null,
new Uint8Array(details.requestBody.raw[0].bytes)));
console.log(postedString)
const body = JSON.parse(postedString);
console.log(body.CenterPoint.Point);
},
{ urls: [url] },
["requestBody"]
);
console.log(tab);
chrome.tabs.sendMessage(tab.id, "your message")
});
}());
My content script is:
console.log("Hi from content script");
chrome.runtime.onMessage.addListener(function (response, sendResponse) {
console.log(response);
});
How do I fix this?

Cross-domain XMLHttpRequest using background pages - Chrome extension version 3

I have used this page Cross-domain XMLHttpRequest using background pages to create a simple extension but I get following errors.
Unchecked runtime.lastError: The message port closed before a response was received.
I used this sample extension then added the contents https://github.com/SimGus/chrome-extension-v3-starter
forground.js
chrome.runtime.sendMessage({
method: 'POST',
action: 'xhttp',
url: 'https://www.stackoverflow.com/search',
data: 'q=something'
}, function (responseText) {
console.log(responseText);
});
service-worker.js
chrome.runtime.onMessage.addListener(function (request, sender, callback) {
if (request.action == "xhttp") {
var xhttp = new XMLHttpRequest();
var method = request.method ? request.method.toUpperCase() : 'GET';
xhttp.onload = function () {
callback(xhttp.responseText);
};
xhttp.onerror = function () {
// Do whatever you want on error. Don't forget to invoke the
// callback to clean up the communication port.
callback();
};
xhttp.open(method, request.url, true);
if (method == 'POST') {
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhttp.send(request.data);
return true; // prevents the callback from being called too early on return
}
});
manifest.json
{
"manifest_version": 3,
"name": "Chrome Extension v3 Starter",
"description": "A minimal example of a chrome extension using manifest v3",
"version": "0.0.1",
"icons": {
"16": "logo/logo-16.png",
"48": "logo/logo-48.png",
"128": "logo/logo-128.png"
},
"options_page": "settings/settings.html",
"action": {
"default_title": "Chrome Addon v3 Starter",
"default_popup": "popup/popup.html"
},
"permissions": [
"https://www.stackoverflow.com/search"
],
"host_permissions": [
"*://*/*"
],
"background": {
"service_worker": "service-worker.js"
},
"content_scripts": [{
"js": ["foreground.js"],
"matches": [ "http://*/*", "https://*/*" ]
}]
}

Overridding XMLHttpRequest Prototype For Chrome Extension

I am trying to intercept all XMLHttpRequests with my extension and I can currently do it to some extent but it does not work fully. I know about webRequests but it does not let me edit the post/get data unlike with the current code below. I can run this code
Inject.js
(function(){
console.log("Injected Send")
var proxiedSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
console.log(this, arguments );
return proxiedSend.apply(this, [].slice.call(arguments));
}
})();
(function(){
console.log("Injected Open")
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
console.log(this, arguments );
return proxiedOpen.apply(this, [].slice.call(arguments));
};
})();
Inside my content script and it will log the "Injected Send" and "Injected Open". I have tested this code and it behaves weirdly.
If you run this code below in the console you would see that it works at intercepting the request but it won't work on any XMLHttpRequests running on the page (old and new objects). It will only intercept XMLHttpRequests made in the console. Another example is this https://www.w3schools.com/code/tryit.asp?filename=GBUKE1JS7IFL . It works in the webpage but I can't get the same behavior by injecting it with an extension.
(function(){
console.log("Injected Send")
var proxiedSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
console.log(this, arguments );
return proxiedSend.apply(this, [].slice.call(arguments));
}
})();
(function(){
console.log("Injected Open")
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
console.log(this, arguments );
return proxiedOpen.apply(this, [].slice.call(arguments));
};
})();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("success")
}
};
xhttp.open("GET", "/", true);
xhttp.send();
This problem is causing my Inject.js to not work.
manifest.json
{
"name": "test",
"version": "0.0.1",
"manifest_version": 2,
"description": "testing xmlhttprequests",
"homepage_url": "http://example.com",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"default_locale": "en",
"background": {
"scripts": [
"src/bg/background.js"
],
"persistent": true
},
"page_action": {
"default_icon": "icons/icon19.png",
"default_title": "page action demo",
"default_popup": "src/page_action/page_action.html"
},
"permissions": [
"tabs",
"*://*.google.com/"
],
"content_scripts": [
{
"matches": [
"https://*/*",
"http://*/*"
],
"run_at": "document_start",
"js": [
"src/inject/inject.js"
]
}
]
}
You need to run it in a DOM script, see Insert code into the page
context using a content script.
-wOxxOm

Chrome Extension failed with chrome.identity.launchWebAuthFlow 'Authorization page could not be loaded.'

I want to authorize with Google after start extension.
I write manifest.json and background.js as below.
current directory structure
manifest.json
{
"manifest_version": 2,
"name": "***************",
"short_name": "DSBOT",
"version": "0.0.1.0",
"description": "**************************",
"icons": {
"16": "images/icon_16.png",
"48": "images/icon_48.png",
"128": "images/icon_128.png"
},
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_icon": {
"19": "images/icon_19.png"
},
"default_popup": "popup.html"
},
"permissions": [
"identity",
"http://*/*",
"https://*/*",
"storage"
],
"oauth2": {
"client_id": **************,
"scopes": ["openid", "email", "profile"],
"hd": "zabuton.co.jp"
}
}
background.js
var clientId = "********************";
var redirectURL = chrome.identity.getRedirectURL();
var url = "https://accounts.google.com/o/oauth2/v2/auth?" +
"scope=email&" +
"response_type=token&" +
"client_id=" + encodeURIComponent(clientId) + "&" +
"redirect_uri=" + encodeURIComponent(redirectURL) + "&" +
"prompt=consent";;
chrome.identity.launchWebAuthFlow({ url: url, interactive: true }, function(redirect_url) {
console.log('redirect_url = ' + redirect_url);
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
After install and run, output log 'Authorization page could not be loaded.'.
redirect_url inside of launchWebAuthFlow is undefined.
If you know my mistake, please teach me.
You don't have the key in your manifest.
You need to copy your extension's key to the manifest.
When you register your application in the Google OAuth console, you'll
provide your application's ID, which will be checked during token
requests. Therefore it's important to have a consistent application ID
during development.
To keep your application ID constant, you need to copy the key in the
installed manifest.json to your source manifest.

Categories

Resources