How to import service classes in Mozilla WebExtensions - firefox-addon-webextensions

I am migrating an addon from mozilla. (Migrating from ADDONS-SDK to WebExtensions technology, however I'm encountering problems when importing the main API classes.
When the plugin was made with ADDON-SDK, the import was done like this:
// Import the main SDK libs to use in the project
var data = require ("sdk / self").
var pageMod = require ("sdk / page-mod");
var utils = require ('sdk / window / utils');
const {Cc, Ci, Cu} = require ("chrome");
const Ac = console;
// Loading services
const OS = Cc ['# mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
const LOADER = Cc ['# mozilla.org/moz/jssubscript-loader;1'].getService(Ci.mozIJSSubScriptLoader);
const IOS = Cc ["# mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
// import browser configuration files
Cu.import ("resource: //gre/modules/Services.jsm");
// Loading other project files
LOADER.loadSubScript ('chrome: //vigiamcviewer/content/HTTP.js');
However, in WebExtensions, I did not find anything like doing the imports.
I've browsed the API and found a good example of the SDK, but nothing like how to do the same with WebExtensions.

Related

Static Files or Images (PNG) doesn't load using C# NET 6 with React.js

I'm using Visual Studio 2022 net 6.0 for create a react project.
I used the ASP.Net Core with React.JS template
Visual Studo 2022 Template
I'm following this tutorial for create a new react application:
https://youtu.be/uii_TmfCjiM
My problem is the part Minute 22:00 of the video.
Where he add a validation in react for add a static file (And PNG image) to be specific.
In the project folder, there is an folder images, and I want to add one of these to a react component.
The idea is to load the image dynamically, using a call to the SQL DB to create the full path
My only difference between my current work space and the video, is I don't have separate projects for the react app and Visual studio Web API.
I used instead the "ASP.Net Core with React.JS" template I mention before.
I follow the tutorial and I add this code to the program.cs file:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Images")),
RequestPath = "/Images"
});
And even did a extra config as well and in the setupProxy.js file, I add the images path to the context:
const context = [
"/api/Participants",
"/api/Questions",
"/Images"
];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context, {
target: target,
secure: false,
headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};
But I'm still having issues when I try to load the image, this is how it looks like:
Web Application
And in the network tab in the DevTools I have this as an Status:
Dev Tools network tab
Any ideas of what could be the problem.
Or what step I'm missing
Best Regards
All after make my search this is the solution I found.
Using the documentation for the http-proxy-middleware, I found in this link:
https://www.npmjs.com/package/http-proxy-middleware
I found the answer for configure the proxy correctly for allow static files.
the program.cs file in .net 6 was correct and these were necessary for allow access the image folder:
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new
PhysicalFileProvider(
Path.Combine(builder.Environment.ContentRootPath,
"Images")),
RequestPath = "/Images"
});
The lines I had to modify in the proxy was the context values.
Noted I had to add the wild card "**" for allow all strings in the context, because you cannot combine string and wildcards. At the end the setupProxy.js :
const context =["/api/Participants/**","/api/Questions/**","/images/**"];
module.exports = function(app) {
const appProxy = createProxyMiddleware(context,{
target: target,secure: false,headers: {
Connection: 'Keep-Alive'
}
});
app.use(appProxy);
};
As you can notice the wild card "*" for all the string path in the context array. Beside you can use this kind of wild card for allow an especific extension, like .png:
"/images/* *.png"

process is undefined in React

I am building a simple React app that generates a QR code from data. I am interested in inspecting the memory usage when the QR code is generated. I am using the built process.memoryUsage() function but the app throws and exception
Uncaught TypeError: process__WEBPACK_IMPORTED_MODULE_1__.process is undefined
I have tested some different solution, i tried to rollback the react script version to "4.0.3" i tried to download the npm polyfill webpack but there is no success.
I am currently using these imports
import React, { useState, useEffect } from 'react';
import process from 'process';
import './App.css';
const QRCode = require('qrcode');
The function looks like this
let stringData = JSON.stringify(qrData);
console.log("Number of chars in data" + " " + stringData.length);
QRCode.toDataURL(stringData, function (err, url) {
if(err) return console.log("error occured")
//window.location.href = url;
})
const used = process.memoryUsage();
for (let key in used) {
console.log(`${key} ${Math.round(used[key] / 1024 / 1024 * 100) / 100} MB`);
}
}
process is a Node.js API and is not available in the browser where your React app is running, which is why you see that error. If there is an available global process object, it is being polyfilled by something in your build tools, and will not have the memoryUsage method.
There is no equivalent API for the browser, but some related APIs do exist. Note that this is an evolving space and some are non-standard, so be sure to read both the spec and documentation before considering any usage:
Device Memory API (MDN)
Performance.memory (MDN)
You are using a built in nodejs package in a react app. Node executes on the server and has access to system level resources. React runs in the browser and does not. See this article for some tips measuring performance in React.

How to set up Hardhat with Typescript support along with React & Typescript?

I was wondering if anyone had create a contract in hardhat and generated & compiled the contract with typechain. Taking the compiled contract and used it in a react app.
I am able to write a contract & generate the necessary files fine using npx hardhat and choosing the option with typescript. npx hardhat compile generates the necessary json and typescript stubbings. Now I am lost on how to bring that into a React app. I also do not want to deploy the contract in the smart contract. Assume the smart contract is deployed (locally is fine). Knowing this, is it possible to use the smart contract in react with type safety.
There are many well written articles on the web about combining react with web3 stuff: https://dev.to/rounakbanik/building-a-web3-frontend-with-react-340c
But basically you have to compile your smart contract to an abi file that can be read by your react webapp.
There are libraries for that (also mentioned in most articles / tutorials)
Hope this helps ;)
In hardhat projects layout, we keep the hardhat stuff in its own directory, maybe named contracts. When you created the .json files, take that json file and copy it in a client directory, maybe create a lib folder. You should have this file
client/lin/MyContract.json
to create the contract, we need to get the abi from json data.
// your directory path might be different
// in next.js it is easy importing from .json, you have to handle it differently in webpack
import abi from '../lib/MyContract.json'
Once you get the abi, you used it as abi.abi.
to create a contract write a function
const getEthereumContract = () => {
// instead of ethereum u might be using a different provider
const provider = new ethers.providers.Web3Provider(ethereum)
const signer = provider.getSigner()
// this is the contract
const MyContract = new ethers.Contract(
contractAddress,
abi.abi,
signer,
)
return MyContract
}
You get the contract address when you run the deploy script.
const main = async () => {
const transactionFactory = await hre.ethers.getContractFactory('Transactions')
const transactionContract = await transactionFactory.deploy()
await transactionContract.deployed()
// GET THIS CONTRACT ADDRESS
console.log('Transactions deployed to:', transactionContract.address)
}
;(async () => {
try {
await main()
process.exit(0)
} catch (error) {
console.error(error)
process.exit(1)
}
})()
Finally you should have this to create the contract:

Why webpack imports all files in subdirectory instead of the right

I have React app which render 300 pages. They are divided into 4 groups. There are common settings, custom settings for each group and settings for each page in .json files. I don't want to load all the settings for all pages, but only those needed for a particular page. I try use require to import necessary file:
const getThemeConfig = (theme) => {
const filePath = `./themes/${theme}/config.json`;
return require(`${filePath}`)
};
const themeConfig = getThemeConfig(currentTheme);
this file is imported, but at the same time the application tries to upload absolutely all .json files in ./themes directory. IDK how to fix it.

Authentication Issue when using Google Cloud Endpoints

I'm currently working on an android app using android studio and the google cloud endpoints module with android studio. So I'm trying to add User authentication through the Firebase Auth so I can provide my users with sign-in options from different users. However whenever I try to add the authentication code to the API in my endpoint class. The apiIssuer and ApiissuerAudience are always unresolved. I've tried everything and I can't fix the issue so I'm assuming I didn't do or did something wrong to affect this part of the code.
package com.example.Kendrickod.myapplication.backend;
import com.example.Kendrickod.myapplication.backend.domain.Profile;
import com.google.api.server.spi.auth.EspAuthenticator;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.config.Named;
/**
* Defines event APIs.
*/
/** An endpoint class we are exposing */
#Api(name = "event",
version = "v1",
namespace = #ApiNamespace(ownerDomain =
"backend.myapplication.Kendrickod.example.com",
ownerName = "backend.myapplication.Kendrickod.example.com",
packagePath = ""),
authenticators = {EspAuthenticator.class},
issuers = {
#ApiIssuer(
name = "firebase",
issuer = "https://securetoken.google.com/YOUR-PROJECT-ID",
jwksUri = "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken#system.gserviceaccount.com")
},
issuerAudiences = {
#ApiIssuerAudience(name = "firebase", audiences = "YOUR-PROJECT-ID")
},
clientIds = {Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID, Constants.IOS_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE})
public class EventApi {
}
You must include this library!
com.google.endpoints:endpoints-framework-auth:1.0.2
it seems trivial but not easy to find out ... I got to try them all.
if you use Android Studio, go to Build / Edit library and dependencies click on the "+" and search for "endpoints-framework"

Resources