PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label electron. Show all posts
Showing posts with label electron. Show all posts

Tuesday, November 8, 2022

[FIXED] How to set custom x, y position of Electron Menu when using BrowserWindow.fromWebContents

 November 08, 2022     electron, javascript, menu, popup     No comments   

Issue

I'm using contextBridge and contextIsolation to create a custom context menu on click and I'm using this example from the docs: https://github.com/electron/electron/blob/main/docs/api/menu.md#render-process

// renderer
window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  ipcRenderer.send('show-context-menu')
})

ipcRenderer.on('context-menu-command', (e, command) => {
  // ...
})

// main
ipcMain.on('show-context-menu', (event) => {
  const template = [
    {
      label: 'Menu Item 1',
      click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
    },
    { type: 'separator' },
    { label: 'Menu Item 2', type: 'checkbox', checked: true }
  ]
  const menu = Menu.buildFromTemplate(template)
  menu.popup(BrowserWindow.fromWebContents(event.sender))
})

This works but the context menu appears right under the mouse. I want to supply a custom x and y. In the docs for menu.popup, I can set an x and y property like this:

menu.popup({
  window: /* my window object /*,
  x: /* x position */,
  y: /* y position */,
})

But I don't know how to add these properties to the object that I get back from BrowserWindow.fromWebContents(event.sender).

I tried these options:

menu.popup({ ...BrowserWindow.fromWebContents(event.sender), x, y } );
// or
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x, y });

and I get this error

Error processing argument at index 1, conversion failure from 
at EventEmitter.a.popup (node:electron/js2c/browser_init:81:3188)

It seems like electron doesn't like converting the results from BrowserWindow.fromWebContents(event.sender) into an object.

I also tried this, but get the same error.

const window = BrowserWindow.fromWebContents(event.sender);
window.x = x;
window.y = y;
menu.popup(window);

Thanks for the help


Solution

The problem ended up being that the x and y variables need to be integers and sometimes they were floats. Putting a Math.round around x and y solved the problem. This worked in the end:

const xRound = Math.round(x);
const yRound = Math.round(y);
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x: xRound, y: yRound } );


Answered By - mhkeller
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to read an output of terminal command line by line in Javascript

 August 17, 2022     electron, javascript, node.js, output, terminal     No comments   

Issue

I am executing a terminal command and want to read output line by line. Here is my code ;

async function executeCommand(command, callback) {
const exec = require('child_process').exec;
await exec(command, (error, stdout, stderr) => { 
    callback(stdout);
});

};

executeCommand("instruments -s devices", (output) => {
       //read output line by line;
    });

Is it possible to read output line by line and how ?


Solution

You can split output on the EOL character to get each line as an entry in an array. Note that this will create a blank entry after the final EOL character, so if you know that the command ends with that (which it probably does), then you should trim/ignore that last entry.

function executeCommand(command, callback) {
  const exec = require('child_process').exec;
  return exec(command, (error, stdout, stderr) => { 
    callback(stdout);
  });
}

executeCommand('ls -l', (output) => {
  const lines = output.split(require('os').EOL);
  if (lines[lines.length - 1] === '') {
    lines.pop();
  }
  for (let i = 0; i < lines.length; i++) {
    console.log(`Line ${i}: ${lines[i]}`);
  }
});

If your concern is that the output may be very long and you need to start processing it before the command finishes or something like that, then you probably want to use spawn() or something else other than exec() (and perhaps look into streams).

function executeCommand(command, args, listener) {
  const spawn = require('child_process').spawn;
  const subprocess = spawn(command, args);
  subprocess.stdout.on('data', listener);
  subprocess.on('error', (err) => {
    console.error(`Failed to start subprocess: ${err}`);
  });
}

executeCommand('ls', ['-l'], (output) => {
  console.log(output.toString());
});


Answered By - Trott
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 23, 2022

[FIXED] What is the best way to transfer certain data to another json document?

 July 23, 2022     electron, javascript, json     No comments   

Issue

Explanation:

I want to make an Electron app [Javascript not jQuary] (or am in the process of doing so) and would like to add a function that puts one config into the "format" of another.

The big file from which I want to take the information I currently read in via "dialog.showOpenDialog" and can also access the json object.

Now to the problem:

The file I get via the dialog is 8000 lines long and contains individual information that I want to pack into a smaller document with about 3000 lines. Important: Individual information have a different name e.g. I want "ABCD: 23" from document 1 in the other as EFG: 23.

Now my two questions:

  1. how can I best provide the smaller file for editing?
  2. how can I convert the individual information without going through each line separately?

bigconfig.json:

{
    "EXAMPLE_CATEGORY": {
        "setting1": 0,
        "setting2": 1,
        "setting3": 115,
        "setting4": 0,
    },

Smallerconfig.json

{
    "EXAMPLE_CATEGORY": {
        "setting7": 115,
        "setting8": 0,
    },

Edit: What I want to achieve is that I can create (and save) a modified file with the information I packed from the big file into the small one.

In the smaller one should be all 3000 felt

Would really appreciate help... yesterday I did a lot of research and used the search engine for several hours.

Thanks in advance


Solution

The only way your smallerConfig object will know which new keys to use is if you define them beforehand. To do this, you must create an object that links the old key names to the new key names. These links would be best defined in one place. The code below holds these links in the conversionTable.

To build the smallerConfig object, you must loop (using for...in) through the bigConfig object one line at a time. Here you will check if the key in the bigConfig object matches a key in the conversionTable (using the in operator). If a matching key is found, then we will use the key’s value in the conversionTable as the new key in the smallerConfig object. Using the bigConfig value in the creation of the smallerConfig object is easy.

let bigConfig = {
    'EXAMPLE_CATEGORY': {
        'setting1': 0,
        'setting2': 1,
        'setting3': 115,
        'setting4': 0
    }
};

let smallerConfig = {
    'EXAMPLE_CATEGORY': {}
};

let conversionTable = {
    'setting3': 'setting7',
    'setting4': 'setting8'
};

// Iterate through the bigConfig object
for (let bigKey in bigConfig.EXAMPLE_CATEGORY) {
    // Check for a matching key in the conversionTable
    if (bigKey in conversionTable) {
        smallerConfig.EXAMPLE_CATEGORY[conversionTable[bigKey]] = bigConfig.EXAMPLE_CATEGORY[bigKey];
    }
}

console.log(smallerConfig);

Output will be:

{
    'EXAMPLE_CATEGORY': {
        'setting7': 115,
        'setting8': 0
    }
}

Finally:

  • Use JSON.parse() to convert the file contents from a string to a Javascript object.
  • Use JSON.stringify() to convert the Javascript object back to a string for writing to the new file.


Answered By - midnight-coding
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 20, 2022

[FIXED] What event should I use for closing client websocket in Electron application?

 April 20, 2022     connection, dom-events, electron, javascript, websocket     No comments   

Issue

I have Electron application. There is websocket connection between server and client side of electron app (another words, I use websocket on index.html).

I need to close websocket connection, when user closes the application. What event should I use for it?

There is mainWindow.on('closed', () => { }); but I have no access to browser code at this point.


Solution

You should use IPC (Internal Process Communication). In the electron framework, there are two processes:

  • Main (The main process creates web pages by creating BrowserWindow instances.)
  • Renderer (The main process manages all web pages and their corresponding renderer processes)

These two can communicate together using IPC. For more details see docs



Answered By - Ashot
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, April 15, 2022

[FIXED] Why after --disable-web-security and deleting x-frame-options header this error still showing?

 April 15, 2022     code-injection, cross-domain, electron, google-chrome, iframe     No comments   

Issue

I'm creating a webapp in electron, a web-crawler with a neural network, which needs all webSecurities to be disabled

i tried modifying the headers (X-Frame-Origin,access-control-allow-origin etc..) , using flags like chrome --allow-file-access-from-files --disable-web-security --user-data-dir="" etc... nothing seems to remove the error above

The iframe is showing the ORIGIN restricted websites after i modified the xframe header, but when i try to access its document, the error above pops

i tried running it in chrome and firefox, and the same behaviour is encoutered

been googling for 4 hours now and i can't seem to find an appropriate answer. if you think this is a duplicated please include a link, it would help a lot

error in chrome devtool


Solution

i found the solution ,the disable site isolation trial should be toggled on :

app.commandLine.appendSwitch('disable-site-isolation-trials')



Answered By - aymen ayoo
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing