web extensions: Update menu on firefox android - firefox-addon-webextensions

Before web extensions, I used NativeWindow.menu.add and achieved this on firefox android.
Add menu I can do this from browser_action.default_title.
Update text from the addon (like '936')
How do I do this in web extensions?
https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Legacy_Firefox_for_Android/API/NativeWindow/menu/add
previous code
// getWindow
const { Cu } = require('chrome');
/**
* get current browser window for firefox addon
*
* #returns {ChromeWindow|null} browser window
* #see https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIWindowMediator#getMostRecentWindow()
*/
module.exports = () => {
/* global Services:false */
Cu.import('resource://gre/modules/Services.jsm');
return Services.wm.getMostRecentWindow('navigator:browser');
};
// index.js
menuId = getWindow().NativeWindow.menu.add({
name: 'Page for Hatebu (-)',
callback: handleClick,
});
getWindow().NativeWindow.menu.update(
menuId,
{
name: `Page for Hatebu (${piece})`,
});

After Firefox 57 you have to use WebExtensions (aka Browser Extensions) for all Firefox extensions.
You can use browserAction to add an item to the Firefox menu on Android. And especially browserAction.setTitle to change the text.

Related

PDFjs not working in safari, blank page. How to solve issue?

I'm using pdfjs-dist "^2.16.105" to import pdf files into fabric as fabric.Images in my React Application. According to the http://fabricjs.com/import-pdf example, this all works in Chrome, Firefox, but does not work in Safari. I'm testing in Safari version 14.1.2. Here's the error in the console when loading react app.
SyntaxError: Unexpected private name #ensureObj. Cannot parse class method with private
name.
I have read that safari versions before 14.5 does not support private classes. How can this problem be solved?
In Safari React application doesn't start, I only see a blank screen.
This is my code
import * as PDFJS from "pdfjs-dist";
import * as pdfjsWorker from "pdfjs-dist/build/pdf.worker.entry";
PDFJS.GlobalWorkerOptions.workerSrc = pdfjsWorker;
...
PDFJS.getDocument({
data: pdfData,
}).promise.then((a) => {
a.getPage(1).then((page) => {
let viewport = page.getViewport({ scale: window.devicePixelRatio });
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
const render_context = {
canvasContext: context,
viewport: viewport,
};
const renderTask = page.render(render_context);
renderTask.promise.then(() => {
const canvasImage = new fabric.Image(canvas, {});
renderCanvasImg(canvasImage);
});
});
});
One possibility is to downgrade pdf-dist library to v2.4.456 since the version v2.13.216 introduced #ensureObj - private fields ES2022 feature (see build/pdf.js).
package.json:
{
dependencies: {
"pdfjs-dist": "v2.4.456",
...
}
...
}
Second possibility would be to use some transpiler (etc. Babel) to downgrade the ES version.

React.js micro frontend subscribe to main app network requests

I have a React.js app (chrome extension micro frontend) that is injected into another frontend app.
I have no permissions to alter the main app code.
Is it possible to subscribe and see the HTTP requests made by the main app?
Thanks.
Here's how you can see what HTTP requests does the main app do:
const windowFetch = window.fetch
window.fetch = function (reqestUrl) {
console.log('reqestUrl: ' + reqestUrl)
console.log('arguments: ' + JSON.stringify(arguments)) // method, headers, body
return windowFetch.apply(this, arguments)
}
Update:
It works when the code is simply pasted into the page console, but unfortunately for the content script, "The window object the content script sees is not the same window object that the page sees."
Solution credit:
https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a
Inspired by:
Access window variable from Content Script
Aditional setup:
manifest.json (V2)
{
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["inject.js"],
"all_frames": true
}
],
"web_accessible_resources": [
"content.js"
]
}
content.js
console.log(window);
inject.js
/**
* injectScript - Inject internal script to available access to the `window`
*
* #param {type} file_path Local path of the internal script.
* #param {type} tag The tag as string, where the script will be append (default: 'body').
* #see {#link http://stackoverflow.com/questions/20499994/access-window-variable-from-content-script}
*/
function injectScript(file_path, tag) {
var node = document.getElementsByTagName(tag)[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file_path);
node.appendChild(script);
}
injectScript(chrome.extension.getURL('content.js'), 'body');
For Manifest V3:
Changes in Manifest:
"web_accessible_resources": [
{
"resources": ["content.js"],
"matches": ["https://*.anywebsite.com/*"]
}
]
Changes in Inject.js
injectScript(chrome.runtime.getURL('content.js'), 'body');

Electron React app white screen + disconnected devtools in build but fine in development?

When I run my app on the development server (npm start) it works fine without any issues in the console.
However, when I build my app (npm run build && electron-builder -m) I get a white screen and disconnected devTools.
Here is my main.js file
const { app, BrowserWindow, screen } = require('electron')
let mainWindow;
function createWindow () {
// Create the browser window.
const { width, height } = screen.getPrimaryDisplay().workAreaSize
const win = new BrowserWindow({
title:"DSL viewer",
width:1050,
height:700,
maxHeight:height,
maxWidth:width,
minHeight:700,
minWidth:1050,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
devTools: true
}
})
win.loadURL('./index.html');
win.on('closed', function () {
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow)
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Here is a screenshot of what the app looks like
Does anyone know what may be causing this or how I can go about debugging it?
Thanks in advance!
It is because electron is unable to find the index.html after build. Change window.loadURL to window.loadURL(__dirname+"/index.html").

Webview context doesn't show up anymore when testing using Appium

I am creating an automation test using Appium and webdriverio:
const wdio = require("webdriverio");
const opts = {
path: "/wd/hub",
port: 4723,
capabilities: {
platformName: "Android",
platformVersion: "11",
deviceName: "Android Emulator",
app: "/path/to/myapk.apk",
automationName: "UiAutomator2",
autoGrantPermissions: true
}
};
async function main() {
const driver = await wdio.remote(opts);
const contexts = await driver.getContexts();
console.log("Contexts:", contexts);
await driver.deleteSession();
}
main();
The problem
When running tests I could see that I used to have two contexts:
NATIVE_APP
WEBVIEW_chrome (or similar, I do not remember exactly the value here)
I then made a change which switched contexts to the webview, there I got an error about the chrome driver not being found. That is when I installed it: npm install "appium-chromedriver".
I do not know if this is what made everything go babanas, but since then, everytime I test, I can only see the native context, no more webview context :(
More info
It is important to point out that I have modified my Android app to include this:
#Override
public void onCreate() {
super.onCreate();
WebView.setWebContentsDebuggingEnabled(true);
}
I can also start chrome://inspect and see the webview is there and even inspect it. But when running tests, the driver cannot see the webview context.
Why? How to fix this?
Turns out that I need to wait for a webview to show up in the app, so this works:
async function main() {
const driver = await wdio.remote(opts);
// Wait a few seconds so the webview properly loads
await new Promise(resolve => setTimeout(resolve, 5000));
const contexts = await driver.getContexts();
console.log("Contexts:", contexts);
await driver.deleteSession();
}

How to make the dev tools not show up on screen by default in Electron?

I am using electron-react-boilerplate to create an Electron-React app. The dev tools show up on the screen by default. How can I make the dev tools only appear when I ask for them and not show up on launch?
Also, there are no errors shown in the console, so the dev tools are not showing up because there's an error.
Just comment or remove this line of code in main.js file (setting devTools to false) this.mainWindow.openDevTools();
(or)
Add the following code to
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
webPreferences: {
devTools: false
}
});
(or)
change the package.json build to npm run build && build --win --x64
(or)
again install npm
If we add devTools: false in webPreferences, DevTools will not show when you start the Electron app. However, it can still be opened by pressing Ctrl + Shift + I.
webPreferences: {
devTools: false
}
Have a look at Slack. It is made with Electron and DevTools does not open when you press Ctrl + Shift + I.
I've had a look at Electron's official documentation, and I found a solution which doesn't allow DevTool's to open when you press Ctrl + Shift + I.
const { app, globalShortcut } = require('electron');
app.on('ready', () => {
// Register a shortcut listener for Ctrl + Shift + I
globalShortcut.register('Control+Shift+I', () => {
// When the user presses Ctrl + Shift + I, this function will get called
// You can modify this function to do other things, but if you just want
// to disable the shortcut, you can just return false
return false;
});
});
But, this will block all other browser's Ctrl + Shift +I
So, you can write the above code whenever your electron app is focused. And, remove it when your app is blur. This way you get a proper solution for this issue.
What makes the Developer Tools appear when the app starts is the line require('electron-debug')() in src/main/main.ts. This function has a showDevTools option which defaults to true, so you should change it to false:
require('electron-debug')({ showDevTools: false });
You will still be able to show the Developer Tools with the shortcut Ctrl + Shift + I or pressing F12, if you want to disable it completely, set webPreferences.devTools to false on new BrowserWindow:
mainWindow = new BrowserWindow({
// ... other settings
webPreferences: {
// ...
devTools: false,
},
});
Just add there these two bold line of code. You will not see devTool after packaging.
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
var debug = false
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
// Open the DevTools.
if(debug) mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Every answer mentions that the keyboard shortcut CTRL + SHIFT + I still works even after disabling devtools using devTools: false.
This is because of the registered accelerator in the Electron BrowserWindow's default menu. All you have to do is remove the menu using mainWindow.removeMenu() and none of the development related shortcut keys will work again. Even the ones like CTRL + R which reloads the page.
Just want to add that, if you want to disable devTools only when in production mode, you can do:
new BrowserWindow({
webPreferences: {
devTools: !app.isPackaged,
},
})
P.S. This also prevents using shortcuts like Ctrl+Shift+I to toggle the devTools.
Just remove the line
mainWindow.webContents.openDevTools(false);
YEAR 2022
Code that loaded the devtools is in src/main/main.ts
Search this following code:
const isDebug =
process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';
if (isDebug) {
require('electron-debug')();
}
you need to disable electron debug by comment it
//require('electron-debug')();

Resources