electron#ipcRenderer JavaScript Examples

The following examples show how to use electron#ipcRenderer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.jsx    From razer-macos with GNU General Public License v2.0 6 votes vote down vote up
constructor(props) {
    super(props);

    this.state = {
      mode: 'device',
      message: null
    };

    ipcRenderer.on('render-view', (event, message) => {
      const {mode} = message;
      this.setState({mode: null, message: null});
      this.setState({mode: mode, message: message});
    })
  }
Example #2
Source File: preload.js    From melvor-mod-manager with MIT License 6 votes vote down vote up
contextBridge.exposeInMainWorld('process', {
  launchMelvor: async (melvorDir, launchMode) => await ipcRenderer.invoke('process', { type: process.launchMelvor, melvorDir, launchMode }),
  openLink: async (url) => await ipcRenderer.invoke('process', { type: process.openLink, url }),
  minimize: () => ipcRenderer.invoke('process', { type: process.minimize }),
  maximize: () => ipcRenderer.invoke('process', { type: process.maximize }),
  exit: () => ipcRenderer.invoke('process', { type: process.exit }),
  getPlatform: () => ipcRenderer.invoke('process', { type: process.getPlatform }),
  getVersion: () => ipcRenderer.invoke('process', { type: process.getVersion })
});
Example #3
Source File: filesystem-api.js    From clipcc-desktop with GNU Affero General Public License v3.0 6 votes vote down vote up
window.showSaveFilePicker = async options => {
    const result = await ipcRenderer.invoke('show-save-dialog', {
        filters: typesToFilterList(options.types),
        suggestedName: options.suggestedName
    });

    if (result.canceled) {
        throw new AbortError('Operation was cancelled by user.');
    }

    const filePath = result.filePath;
    return new WrappedFileHandle(filePath);
};
Example #4
Source File: App.js    From ciphora with MIT License 6 votes vote down vote up
// Activates the selected chat
  activateChat (chatId) {
    // Check if clicked chat already active
    if (chatId === this.state.activeChatId) {
      return
    }
    // Remove compose chat when user moves to another chat
    if (this.state.activeChatId === COMPOSE_CHAT_ID) {
      this.deleteComposeChat()
    }

    this.setState({ activeChatId: chatId })
    ipcRenderer.send('activate-chat', chatId)
  }
Example #5
Source File: preload.js    From among-us-proxy with MIT License 6 votes vote down vote up
contextBridge.exposeInMainWorld('ipcRenderer', {
  send: (method, arg) => {
    ipcRenderer.send(method, arg);
  },
  on: (m, f) => {
    ipcRenderer.on(m, f);
  },
  removeListener: (m, f) => {
    ipcRenderer.removeListener(m, f);
  },
});
Example #6
Source File: ApiHandler.js    From Memocast with MIT License 6 votes vote down vote up
/**
 * 在本地注册对应的事件句柄,用于解决对应的事件
 * @param {string} channel 频道名称
 * @param {Function} api 操作函数
 * @returns {Promise<void>}
 */
async function handleApi (channel, api) {
  ipcRenderer.setMaxListeners(200000)
  ipcRenderer.on(channel, async (event, ...args) => {
    try {
      return await api(event, ...args)
    } catch (err) {
      console.error(err)
      return {
        error: {
          code: err.code,
          message: err.message,
          externCode: err.externCode,
          sourceStack: err.stack,
          isNetworkError: err.isAxiosError,
          networkStatus: err.response?.status
        }
      }
    }
  })
}
Example #7
Source File: about.jsx    From desktop with GNU General Public License v3.0 6 votes vote down vote up
ipcRenderer.invoke('get-debug-info').then((info) => {
  ReactDOM.render((
    <main>
      <h1>TurboWarp Desktop v{info.version}</h1>
      <p>
        <i>
          {'(Debug info: '}
          {`v${info.version} ${info.env}, `}
          {`${info.platform} ${info.arch}${info.runningUnderTranslation ? '-translated' : ''}, `}
          {`Electron ${info.electron}`}
          {')'}
        </i>
      </p>
      <p>TurboWarp is a mod of Scratch with a compiler and more features. TurboWarp is not affiliated with Scratch, the Scratch Team, or the Scratch Foundation. Learn more at <a href="https://desktop.turbowarp.org" target="_blank" rel="noreferrer">https://desktop.turbowarp.org</a>.</p>
      <p>TurboWarp Desktop is licensed under the GNU General Public License v3.0. The source code is published <a href="https://github.com/TurboWarp/" target="_blank" rel="noreferrer">on GitHub</a>. You can read the license below:</p>
      <pre>{licenseText}</pre>
    </main>
  ), require('../app-target'));
});
Example #8
Source File: index.js    From SnipCommand with MIT License 6 votes vote down vote up
componentDidMount() {
        const { isWindows } = this.state;

        ipcRenderer.on('appMenu', (event, args) => {
            if (args.type === 'preferences') {
                this.setState({ showSettingsModal: true, settingsSelectedTab: args.tab });
            }
        })

        if (isWindows) {
            this.onResizeWindow();
            this.refMenu.addEventListener('click', this.onClickMenu);
            this.refClose.addEventListener('click', this.onClickClose);
            this.refMinimize.addEventListener('click', this.onClickMinimize);
            this.refMaximize.addEventListener('click', this.onClickMaximize);
            window.addEventListener('resize', this.onResizeWindow);
        }
    }
Example #9
Source File: index.js    From multistream with MIT License 6 votes vote down vote up
function Prevent(){

  const dispatch = useDispatch();

  const isPreventVisible = useSelector(state => {
    console.log(state);
    return state.isPreventVisible;
  })
  
  function handleCancel(){
    dispatch({
      type: "UPDATE_IS_PREVENT_VISIBLE",
      isVisible: false,
    })
  }
  function handleConfirm() {
    ipcRenderer.send('setIsStreaming', false);
    remote.app.quit();
  }
  return isPreventVisible ? (
    <Container >
      <Box>
        <Titlebar>
          <div>X</div>
        </Titlebar>
        <div className="content">
          Are you sure you want to close? All your streams will be finished.
          <div className="actions">
            <a onClick={handleCancel}>Cancel</a>
            <button className="confirm" onClick={handleConfirm}>Yes, i'm sure</button>
          </div>
        </div>
      </Box>
    </Container>
  ) : <></>;
}
Example #10
Source File: electron-preload.js    From loa-details with GNU General Public License v3.0 6 votes vote down vote up
contextBridge.exposeInMainWorld("messageApi", {
  send: (channel, data) => {
    let validChannels = ["window-to-main"];

    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data);
    }
  },
  receive: (channel, func) => {
    let validChannels = [
      "updater-message",
      "pcap-on-message",
      "pcap-on-state-change",
      "pcap-on-reset-state",
      "on-settings-change",
      "parsed-logs-list",
      "parsed-log",
      "log-parser-status",
      "on-restore-from-taskbar",
      "shortcut-action",
      "selected-log-path-folder",
    ];

    if (validChannels.includes(channel)) {
      // Deliberately strip event as it includes `sender`
      ipcRenderer.on(channel, (event, ...args) => func(...args));
    }
  },
});
Example #11
Source File: LicenseActivator.js    From example-electron-license-activation with MIT License 6 votes vote down vote up
useDeviceInfoStore = createStore(set => ({
  version: `v${ipcRenderer.sendSync('GET_APP_VERSION')}`,
  electron: `v${process.versions.electron}`,
  node: `v${process.versions.node}`,
  platform: process.platform,
  name: os.hostname(),

  setName: name => set(state => ({ ...state, name }))
}))
Example #12
Source File: TXTResolver.electron.renderer.js    From mymonero-android-js with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
startObserving_ipc () {
    const self = this
    ipcRenderer.on(
      'TXTRecords-Callback',
      function (event, arg) {
        const uuid = arg.uuid
        const callback = self.callbacksByUUID[uuid]
        delete self.callbacksByUUID[uuid]
        //
        if (arg.err && typeof arg.err !== 'undefined') {
          callback(arg.err)
          return
        }
        callback(null, arg.records, arg.dnssec_used, arg.secured, arg.dnssec_fail_reason)
      }
    )
  }
Example #13
Source File: AlfwDisk.js    From ntfstool with MIT License 6 votes vote down vote up
function setDiskMountPrending(index,setStatus) {
    var diskList = getStoreForDiskList();
    if(typeof diskList["ext"] != "undefined"){
        for(var i in diskList["ext"]){
            if(diskList["ext"][i].index == index){
                diskList["ext"][i].status =  setStatus;
            }
        }
    }

    setStoreForDiskList(diskList,function () {
        ipcRenderer.send("IPCMain",AlConst.GlobalViewUpdate);
    })
}
Example #14
Source File: Collection.jsx    From thinkord-desktop with GNU General Public License v3.0 6 votes vote down vote up
componentDidMount() {
    ipcRenderer.once('init-collection-title', (event, title) => {
      this.setState({ title: title });
    });

    // When you press stop recording, then you could save collection
    ipcRenderer.on('savebutton', () => {
      this.setState({ saveSign: !this.state.saveSign });
    });

    // When you press start recording, the you could not save collection
    ipcRenderer.on('hidesavebutton', () => {
      this.setState({ saveSign: !this.state.saveSign });
    });

    // With Mousetrap package, you should specify "Ctrl" as "ctrl"
    Mousetrap.bind(['ctrl+s', 'ctrl+S'], () => {
      this.saveChange();
    });

    Mousetrap.bind(['ctrl+z', 'ctrl+Z'], () => {
      ipcRenderer.send('pre-step-click');
    });

    Mousetrap.bind(['ctrl+y', 'ctrl+Y'], () => {
      ipcRenderer.send('next-step-click');
    });
  }
Example #15
Source File: index.js    From neutron with Mozilla Public License 2.0 6 votes vote down vote up
SectionReset = () => (
  <List disablePadding dense>
    <ListItem
      button
      onClick={() => {
        dialog.showMessageBox(getCurrentWindow(), {
          type: 'question',
          buttons: ['Reset Now', 'Cancel'],
          message: `Are you sure? All preferences will be restored to their original defaults. Browsing data & ${getWorkspaceFriendlyName(true).toLowerCase()} won't be affected. This action cannot be undone.`,
          cancelId: 1,
        }).then(({ response }) => {
          if (response === 0) {
            ipcRenderer.once('set-preferences', () => {
              enqueueRequestRestartSnackbar();
            });
            requestResetPreferences();
          }
        }).catch(console.log); // eslint-disable-line
      }}
    >
      <ListItemText primary="Restore preferences to their original defaults" />
      <ChevronRightIcon color="action" />
    </ListItem>
  </List>
)
Example #16
Source File: CustomColor2.jsx    From razer-macos with GNU General Public License v2.0 5 votes vote down vote up
export default function CustomColor2({ deviceSelected }) {

  const componentToHex = (c) => {
    if (typeof c === 'undefined') {
      return '00';
    }
    var hex = c.toString(16);
    return hex.length == 1 ? '0' + hex : hex;
  };

  const rgbToHex = ({ r, g, b }) => {
    return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
  };

  const [currentColor, setCurrentColor] = useState({
    hex: rgbToHex(deviceSelected.settings.customColor2.rgb),
    rgb: deviceSelected.settings.customColor2.rgb,
  });
  const handleChange = (newColor) => {
    setCurrentColor(newColor);
  };

  const handleClick = () => {
    deviceSelected.settings.customColor2 = currentColor;
    let payload = {
      device: deviceSelected,
    };
    ipcRenderer.send('request-set-custom-color', payload);
  };
  const styles = { 'default': { picker: { background: '#202124', boxShadow: 'none'}, body: {
        padding: '12px 0 0'
      } }};
  return (
    <div>
      <p>Secondary custom color selection (Starlight Dual Mode only)</p>
      <div className='control'>
        <ChromePicker color={currentColor} onChange={handleChange} width='100%' disableAlpha={true} styles={styles} defaultView={'rgb'}/>
      </div>
      <div className='control'>
        <button onClick={handleClick}>Save custom color</button>
      </div>
    </div>
  );
}
Example #17
Source File: preload.js    From melvor-mod-manager with MIT License 5 votes vote down vote up
contextBridge.exposeInMainWorld('file', {
  // Returns generated manifest (for validation/renaming) and path
  openScript: async () => await ipcRenderer.invoke('file', { type: file.openScript }),
  // Returns path to opened directory
  openDir: async () => await ipcRenderer.invoke('file', { type: file.openDir }),
  // Returns true/false based on if Melvor is detected at path
  validateMelvorDir: async (dir) => await ipcRenderer.invoke('file', { type: file.validateMelvorDir, dir })
});
Example #18
Source File: ScratchDesktopAppStateHOC.jsx    From clipcc-desktop with GNU Affero General Public License v3.0 5 votes vote down vote up
ScratchDesktopAppStateHOC = function (WrappedComponent) {
    class ScratchDesktopAppStateComponent extends React.Component {
        constructor (props) {
            super(props);
            bindAll(this, [
                'handleTelemetryModalOptIn',
                'handleTelemetryModalOptOut'
            ]);
            this.state = {
                // use `sendSync` because this should be set before first render
                telemetryDidOptIn: ipcRenderer.sendSync('getTelemetryDidOptIn')
            };
        }
        handleTelemetryModalOptIn () {
            ipcRenderer.send('setTelemetryDidOptIn', true);
            ipcRenderer.invoke('getTelemetryDidOptIn').then(telemetryDidOptIn => {
                this.setState({telemetryDidOptIn});
            });
        }
        handleTelemetryModalOptOut () {
            ipcRenderer.send('setTelemetryDidOptIn', false);
            ipcRenderer.invoke('getTelemetryDidOptIn').then(telemetryDidOptIn => {
                this.setState({telemetryDidOptIn});
            });
        }
        render () {
            const shouldShowTelemetryModal = (typeof ipcRenderer.sendSync('getTelemetryDidOptIn') !== 'boolean');

            return (<WrappedComponent
                isTelemetryEnabled={this.state.telemetryDidOptIn}
                onTelemetryModalOptIn={this.handleTelemetryModalOptIn}
                onTelemetryModalOptOut={this.handleTelemetryModalOptOut}
                showTelemetryModal={shouldShowTelemetryModal}

                // allow passed-in props to override any of the above
                {...this.props}
            />);
        }
    }

    return ScratchDesktopAppStateComponent;
}
Example #19
Source File: App.js    From ciphora with MIT License 5 votes vote down vote up
componentDidMount () {
    // Init notifications via the context
    notifications = this.context
    // Let main process show notifications
    ipcRenderer.on('notify', (event, ...args) => notifications.show(...args))
    // Load state from main if not already loaded
    ipcRenderer.send('do-update-state')
  }
Example #20
Source File: preload.js    From juggernaut-desktop with MIT License 5 votes vote down vote up
// Provide access to ipcRenderer.
window.ipcRenderer = ipcRenderer;
Example #21
Source File: addon-settings.jsx    From desktop with GNU General Public License v3.0 5 votes vote down vote up
onExportSettings = settings => {
  ipcRenderer.send('export-addon-settings', settings);
}
Example #22
Source File: api.js    From dev-sidecar with Mozilla Public License 2.0 5 votes vote down vote up
export function apiInit (app) {
  const invoke = (api, args) => {
    return ipcRenderer.invoke('apiInvoke', [api, args]).catch(e => {
      app.$notification.error({
        message: 'Api invoke error',
        description: e.message
      })
    })
  }
  const send = (channel, message) => {
    console.log('do send,', channel, message)
    return ipcRenderer.send(channel, message)
  }

  apiObj = {
    ipc: {
      on (channel, callback) {
        ipcRenderer.on(channel, callback)
      },
      removeAllListeners (channel) {
        ipcRenderer.removeAllListeners(channel)
      },
      invoke,
      send,
      openExternal (href) {
        shell.openExternal(href)
      },
      openPath (file) {
        shell.openPath(file)
      }
    }
  }

  const bindApi = (api, param1) => {
    lodash.set(apiObj, api, (param2) => {
      return invoke(api, param2 || param1)
    })
  }

  if (!inited) {
    return invoke('getApiList').then(list => {
      inited = true
      for (const item of list) {
        bindApi(item)
      }
      console.log('api inited:', apiObj)
      return apiObj
    })
  }

  return new Promise(resolve => {
    resolve(apiObj)
  })
}
Example #23
Source File: electron-preload.js    From follow with GNU General Public License v3.0 5 votes vote down vote up
contextBridge.exposeInMainWorld("ipc", {
  getFileTypeFromBuffer: async (buf) => {
    return await FileType.fromBuffer(buf);
  },
  invoke: async (channel, arg1, arg2, arg3, arg4, arg5) => {
    return await ipcRenderer.invoke(channel, arg1, arg2, arg3, arg4, arg5);
  },
  send: (channel, data) => {
    if (validChannels.includes(channel)) {
      console.log("ipc.send...");
      ipcRenderer.send(channel, data);
    }
  },
  on: (channel, func) => {
    if (validChannels.includes(channel)) {
      // Strip event as it includes `sender` and is a security risk
      console.log("ipc.on...");
      ipcRenderer.on(channel, (event, ...args) => func(...args));
    }
  },
  once: (channel, callback) => {
    if (validChannels.includes(channel)) {
      console.log("ipc.once...");
      const newCallback = (_, data) => callback(data);
      ipcRenderer.once(channel, newCallback);
    }
  },
  removeListener: (channel, callback) => {
    if (validChannels.includes(channel)) {
      console.log("ipc.removeListener...");
      ipcRenderer.removeListener(channel, callback);
    }
  },
  removeAllListeners: (channel) => {
    if (validChannels.includes(channel)) {
      console.log("ipc.removeAllListeners...");
      ipcRenderer.removeAllListeners(channel);
    }
  },
});
Example #24
Source File: AlfwShell.js    From ntfstool with MIT License 5 votes vote down vote up
/**
 * exec the shell code by root
 * force Ignore result
 * @param shell
 * @param force
 * @returns {Promise}
 */
export function execShellSudo(shell, force = false) {
    return new Promise((resolve, reject) => {
        var password = getSudoPwd();
        try {
            exec(`echo '${password}'|sudo  -Sk ${shell}`, (error, stdout, stderr) => {
                stderr = stderr.replace( /^Password:/gi , '')
                saveLog.log("execShellSudo", {
                    code: "[SUDO]" + shell,
                    stdout: stdout,
                    stderr: stderr,
                    // error:error
                })
                if (force == true) {
                    resolve();
                    return;
                }
                if (stderr) {
                    if (checkIncorrectPasswordStr(stderr)) {
                        checkSudoPassword().then(res => {
                            if (!res) {
                                reject(stderr);
                                return;
                            }
                        });
                    }else if(!checkFuseStr(stderr)){
                        ipcRenderer.send("IPCMain",AlConst.InstallFuseEvent);
                    }else if(!checkNotSudoer(stderr)){
                        console.warn("checkNotSudoer ok");
                        ipcRenderer.send("IPCMain",{
                            name:AlConst.NotSudoerEvent,
                            data:stderr
                        });
                    }  else {
                        reject(stderr);
                        return;
                    }
                } else {
                    resolve(stdout, stderr)
                }
            });
        } catch (e) {
            saveLog.error(e, "execShellSudo");
        }
    })
}
Example #25
Source File: notificationsRequester.js    From Docketeer with MIT License 5 votes vote down vote up
sendNotification = async (
  notificationType,
  containerId,
  stat,
  triggeringValue,
  containerObject,
) => {

  // Pull the current state, note we do this within this function as opposed to accessing the global state variable in the file because contact preferences may have been updated since the initialization of state variable in the file.
  const currentState = store.getState();
  const contactPreference = currentState.session.contact_pref;
  const email = currentState.session.email;
  // If the user's contact preferences are set to phone
  if (contactPreference === 'phone'){
    // Construct the message body which will be used to send a text
    const body = {
      mobileNumber: state.session.phone,
      triggeringEvent: constructNotificationMessage(
        notificationType,
        stat,
        triggeringValue,
        containerId
      ),
    };
  
    // On the ipcRenderer object (Inter-Process Communication), emit an event 'post-event' with the body
    return await ipcRenderer.invoke('post-event', body);
  }

  // Else if the user's contact preferences are set to email, or null (default to email)

  const date = new Date();
  const dateString = date.toLocaleDateString();
  const timeString = date.toLocaleTimeString();
  const type = notificationType === 'CPU' ? notificationType : notificationType.toLowerCase();
  const stopped = type === 'stopped' ? 'true' : 'false';
  
  const body = {
    email,
    containerName: (stopped === 'true' ? containerObject.Names : containerObject.Name),
    time: timeString,
    date: dateString,
    stopped,
    percent: stat,
    type,
    threshold: triggeringValue,
  };

  await ipcRenderer.invoke('email-event', body);
}
Example #26
Source File: index.js    From neutron with Mozilla Public License 2.0 5 votes vote down vote up
DisplayMedia = () => {
  const [sources, setSources] = useState([]);

  useEffect(() => {
    getDesktopCapturerSourcesAsync({ types: ['window', 'screen'] })
      .then((res) => {
        setSources(res);
      });
  }, [setSources]);

  const screenSources = sources.filter((source) => source.id.startsWith('screen'));
  const windowSources = sources.filter((source) => source.id.startsWith('window'));
  // remove first item as it is the display media window itself
  windowSources.shift();

  return (
    <Box
      sx={{
        height: 1,
        width: 1,
        py: 2,
        px: 0,
        overflow: 'auto',
      }}
    >
      <Typography
        variant="body2"
        sx={{ px: 2 }}
      >
        The app wants to use the contents of your screen. Choose what you’d like to share.
      </Typography>
      <List>
        <ListSubheader disableSticky>Screens</ListSubheader>
        {screenSources.map((source) => (
          <ListItem
            key={source.id}
            button
            onClick={() => {
              ipcRenderer.send('display-media-selected', source.id);
            }}
          >
            <ListItemText primary={source.name} />
          </ListItem>
        ))}
        <Divider />
        <ListSubheader disableSticky>Windows</ListSubheader>
        {windowSources.map((source) => (
          <ListItem
            key={source.id}
            button
            onClick={() => {
              ipcRenderer.send('display-media-selected', source.id);
            }}
          >
            <ListItemText primary={source.name} />
          </ListItem>
        ))}
      </List>
    </Box>
  );
}