Hello:
I tried to write one chrome extension, which get some Json format data from content script, and send it to localhost http server.
I use Node.js version 15.10.0 on Windows 10.
My current manifest.json look like this:
{
"manifest_version": 2,
"name": "DOMJsonData",
"description": "Extension to post data to http server with fetch",
"version": "1.0",
"default_locale": "en",
"icons": {
"128": "icons/icon128.png",
"48": "icons/icon48.png",
"16": "icons/icon16.png"
},
"browser_action": {
"default_icon": "icons/icon16.png",
"default_popup": "src/popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["lib/jquery.min.js", "src/content.js"]
}
],
"permissions": ["tabs", "activeTab", "contextMenus", "storage" ],
"background": {
"scripts": ["src/background.js"]
},
"web_accessible_resources": [
"lib/",
"src/"
]
}
I installed node-fetch npm package, version: 2.6.1
I had the following background.js file:
const fetch = require('node-fetch');
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "export_dom_data" ) {
console.log("Post data to http server");
fetch('http://localhost:3000/', {
method: 'post',
body: request.data
}).then(function(response) {
return response.text();
}).then(function(data) {
console.log(data);
});
}
}
);
I also ran http-echo-server on localhost (npm version 2.1.1), if I wrote the following JavaScript to post http data to localhost http-echo-server, it worked. The code was like this:
const fetch = require('node-fetch');
let json_data = {
npm_title: "node-fetch",
version: "2.6.1"
}
fetch('http://localhost:3000/', {
method: 'POST',
body: JSON.stringify(json_data),
headers: { 'Content-Type': 'application/json' }
}).then(res => res.text())
.then(json => console.log(json))
.catch(err => console.log(err))
I have the following questions:
- How I can change manifest.json, so my Background.js can use the “node-fetch” npm package. For jquery, I can download jquery.min.js, and put it in folder “lib”, which is easy.
However, when I install node-fetch npm package, I can’t find such min.js file for node-fetch package. I looked at your extension, but I didn’t find any manifest.json file for your extension; besides, your extension is way more complicated. I only need to send some Json data to a fixed stand-alone http server. (I will use C# to write a http server later, but now, simply use http-echo-server for testing.)
- I found Google has something like background fetch: https://developers.google.com/web/updates/2018/12/background-fetch
I want to know if I can use such background fetch API to send out some Json data to an http server in the localhost, then I don’t have to install other npm package or have other headache like find min.js file for npm packages.
Please advise!