Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Electron BrowserWindow之间传参 #82

Open
ionepub opened this issue Oct 28, 2018 · 0 comments
Open

Electron BrowserWindow之间传参 #82

ionepub opened this issue Oct 28, 2018 · 0 comments

Comments

@ionepub
Copy link
Owner

ionepub commented Oct 28, 2018

一、主进程与BrowserWindow之间传参

可以通过ipc传参,ipc-main在主进程中使用,ipc-renderer在渲染进程中使用。

1.主进程向渲染进程传参

参考:https://electronjs.org/docs/api/web-contents#contentssendchannel-arg1-arg2-

main.js

win.webContents.on('did-finish-load', () => {
    win.webContents.send('ping', 'whoooooooh!');
})

render.js

const { ipcRenderer } = require('electron')
ipcRenderer.on('ping', function(event, message){
	console.log(message);
});

2.渲染进程向主进程传参

参考:https://electronjs.org/docs/api/ipc-main

render.js

const {ipcRenderer} = require('electron')
# 发送异步消息
ipcRenderer.send('asynchronous-message', 'ping')
# 发送同步消息
ipcRenderer.sendSync('synchronous-message', 'ping2')

main.js

const {ipcMain} = require('electron')
# 接收异步消息
ipcMain.on('asynchronous-message', (event, arg) => {
    console.log(arg) // prints "ping"
})
# 接收同步消息
ipcMain.on('synchronous-message', (event, arg) => {
    console.log(arg) // prints "ping2"
})

二、渲染进程间传参(BrowserWindow)

方式一

参考:https://www.cnblogs.com/xuhongli/p/7076533.html

render1.js

win.webContents.on('did-finish-load', function(){
	win.webContents.send('pageData', {'id': 123});
});

render2.js

const { ipcRenderer } = require('electron')
ipcRenderer.on('pageData', function(event, message){
	console.log(message); // {id:123}
});

方式二

render1.js

var id = 123;
win.loadURL('file://'+__dirname+'/detail.html?id='+id);
// 或者
win.loadURL(`file://${__dirname}/detail.html?id=123`)

render2.js

// 从URL中获取参数
var id = getQueryVariable('id');
console.log(id); // 123

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

三、页面间数据共享

通过localStorage等方式共享数据,或者在主进程中存储全局变量,然后各个渲染进程调用,参考:https://electronjs.org/docs/faq#how-to-share-data-between-web-pages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant