正在使用electron和node.js做桌面應(yīng)用,需要實(shí)時(shí)監(jiān)聽(tīng)是否有網(wǎng)絡(luò)連接,node或者electron是否可以做到
問(wèn)題描述
如標(biāo)題,實(shí)時(shí)監(jiān)聽(tīng)網(wǎng)絡(luò)情況,如果沒(méi)有網(wǎng)絡(luò)情況就會(huì)顯示脫機(jī),請(qǐng)問(wèn)node或者electron是否可以做到?求教
問(wèn)題解答
回答1:試試navigator.onLine,不需要node.js不需要electron,普通網(wǎng)頁(yè)都能判斷是否有網(wǎng)絡(luò)
回答2:官方文檔:http://electron.atom.io/docs/...
回答3:function isOnline(user_callback){ /** * Show a warning to the user. * You can retry in the dialog until a internet connection * is active. */ var message = function(){const {dialog} = require(’electron’).remote;return dialog.showMessageBox({ title:'There’s no internet', message:'No internet available, do you want to try again?', type:’warning’, buttons:['Try again please','I don’t want to work anyway'], defaultId: 0},function(index){ // if clicked 'Try again please' if(index == 0){execute(); }}) }; var execute = function(){if(navigator.onLine){ // Execute action if internet available. user_callback();}else{ // Show warning to user // And 'retry' to connect message();} }; // Verify for first time execute();}// Use it, the alert('Hello world'); will be executed only if there’s an active internet connection.isOnline(function(){ alert('Hello world !');});
you can check out this blog for details.
回答4:監(jiān)聽(tīng)navigator.onLine可以實(shí)現(xiàn),感謝兩位的幫助
window.addEventListener('offline', function(e) { alert('offline')})window.addEventListener('online', function(e) { alert('online')})
