sachin murali
sachin murali

Reputation: 489

How to take screenshot using electronjs?

I'm building a cross-platform desktop application. I'm using electronjs framework for my desktop app development.And I want to add a functionality of taking screenshot every 5 minutes when my app starts!

help will be appreciated my main.js

// Modules to control application life and create native browser window
const {app, BrowserWindow,Tray,Menu} = require('electron')
const path = require('path')
const iconz = path.join(__dirname,'/img/download.png')
const fs = require('fs')
var config = require('./login.json');
const shell = require('electron').shell



let tray = null



function createWindow () {

  tray = new Tray(iconz)
  const contextMenu = Menu.buildFromTemplate([
    { label: 'User:'+ config.username, type: 'radio',enabled:false},
    {type:'separator'},
    { label: 'Show DeskTime', type: 'radio',
    click() { 
      shell.openExternal('http://coinmarketcap.com')
      } 
    },
    {type:'separator'},
    { label: 'Private Time', type: 'radio',
    click() { 
      checked:true
      } 
    },
    {type:'separator'},
    { label: 'LogOut', type: 'radio' },
    {type:'separator'},
    { label: 'Quit', type: 'radio',
      click() { 
          app.quit() 
      }
    }
  ])
  tray.setToolTip('This is my application.')
  tray.setContextMenu(contextMenu)



  console.log(config.username + ' ' + config.password);
  if(config.username == ""){

   // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

 // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  }



  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// 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.
app.on('window-all-closed', function () {
  // On macOS 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 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.

my index.html

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}

input[type=text], input[type=password] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  width: 100%;
}

button:hover {
  opacity: 0.8;
}

.cancelbtn {
  width: auto;
  padding: 10px 18px;
  background-color: #f44336;
}

.imgcontainer {
  text-align: center;
  margin: 12px 0 6px 0;
}

img.avatar {
  width: 20%;
  border-radius: 40%;
}

.container {
  padding: 16px;
}

span.psw {
  float: right;
  padding-top: 16px;
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
  span.psw {
     display: block;
     float: none;
  }
  .cancelbtn {
     width: 100%;
  }
}
</style>
</head>
<body>

<h2>Login Form</h2>

<form action="/action_page.php" method="post">
  <div class="imgcontainer">
    <img src="login_logo.png" alt="Avatar" class="avatar">
  </div>

  <div class="container">
    <label for="uname"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="uname" required>

    <label for="psw"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit">Login</button>
    <label>
      <input type="checkbox" checked="checked" name="remember"> Remember me
    </label>

  </div>

  <div class="container" style="background-color:#f1f1f1">


    <span class="psw">Forgot <a href="#">password?</a></span>
  </div>
</form>
<label id="screenshot-path">Path:</label>
<button  id="screen-shot" type="button" class="cancelbtn">Singup</button>
</body>

   <script src="./renderer.js"></script>


</html>




My codes are given above, please go through this and help me to take screenshot on a certain interval.And also how to save in screen shots in predefined folder.

Upvotes: 4

Views: 8945

Answers (1)

namila007
namila007

Reputation: 1134

You can use contents.capturePage([rect]) on your main process. if you omits rect args it will capture the whole window. This will return a promise with native image .

  1. To capture it on every 5 minute, you can set a setInterval(<function>,<time in millis>)
  2. To save on specific folder you can use path module

ex:

const path = require('path')
const myFolderPath = path.join(__dirname, "myfolderinsideProject")
fs.writeFile(path.join(myFolderPath,`test${count}.png`), ....)

example code to save Captured window on current project folder:

// Modules to control application life and create native browser window
const {app, BrowserWindow } = require('electron')
const path = require('path')
const fs = require('fs')
let mainWindow, count=0;
function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// 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.
app.on('window-all-closed', function () {
  // On macOS 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 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()
})

//starting when the app is ready
app.on('ready', () => {
  //setting the time interval for 3 second (3000 in millis)
  setInterval(()=>{
    console.log(`Capturing Count: ${count}`)
    //start capturing the window
    mainWindow.webContents.capturePage().then(image => 
    {
      //writing  image to the disk
          fs.writeFile(`test${count}.png`, image.toPNG(), (err) => {
          if (err) throw err
          console.log('Image Saved')
          count++
          })
    })
    }, 3000); //tome in millis
  });

or you can use this npm package on renderer process

Upvotes: 7

Related Questions