diff --git a/lib/common/asar_init.js b/lib/common/asar_init.js index 85bb828583bc..1b24cd57aa46 100644 --- a/lib/common/asar_init.js +++ b/lib/common/asar_init.js @@ -1,20 +1,20 @@ -(function () { - return function(process, require, asarSource) { +;(function () { + return function (process, require, asarSource) { // Make asar.coffee accessible via "require". - process.binding('natives').ATOM_SHELL_ASAR = asarSource; + process.binding('natives').ATOM_SHELL_ASAR = asarSource // Monkey-patch the fs module. - require('ATOM_SHELL_ASAR').wrapFsWithAsar(require('fs')); + require('ATOM_SHELL_ASAR').wrapFsWithAsar(require('fs')) // Make graceful-fs work with asar. - var source = process.binding('natives'); - source['original-fs'] = source.fs; + var source = process.binding('natives') + source['original-fs'] = source.fs return source['fs'] = ` -var nativeModule = new process.NativeModule('original-fs'); -nativeModule.cache(); -nativeModule.compile(); -var asar = require('ATOM_SHELL_ASAR'); -asar.wrapFsWithAsar(nativeModule.exports); -module.exports = nativeModule.exports`; - }; -})(); +var nativeModule = new process.NativeModule('original-fs') +nativeModule.cache() +nativeModule.compile() +var asar = require('ATOM_SHELL_ASAR') +asar.wrapFsWithAsar(nativeModule.exports) +module.exports = nativeModule.exports` + } +})() diff --git a/lib/common/init.js b/lib/common/init.js index 923ef910886d..221febb0c37a 100644 --- a/lib/common/init.js +++ b/lib/common/init.js @@ -1,47 +1,46 @@ -const path = require('path'); -const timers = require('timers'); -const Module = require('module'); +const path = require('path') +const timers = require('timers') +const Module = require('module') -process.atomBinding = function(name) { +process.atomBinding = function (name) { try { - return process.binding("atom_" + process.type + "_" + name); + return process.binding('atom_' + process.type + '_' + name) } catch (error) { if (/No such module/.test(error.message)) { - return process.binding("atom_common_" + name); + return process.binding('atom_common_' + name) } } -}; +} if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { // Add common/api/lib to module search paths. - Module.globalPaths.push(path.join(__dirname, 'api')); + Module.globalPaths.push(path.join(__dirname, 'api')) } - // setImmediate and process.nextTick makes use of uv_check and uv_prepare to // run the callbacks, however since we only run uv loop on requests, the // callbacks wouldn't be called until something else activated the uv loop, // which would delay the callbacks for arbitrary long time. So we should // initiatively activate the uv loop once setImmediate and process.nextTick is // called. -var wrapWithActivateUvLoop = function(func) { - return function() { - process.activateUvLoop(); - return func.apply(this, arguments); - }; -}; +var wrapWithActivateUvLoop = function (func) { + return function () { + process.activateUvLoop() + return func.apply(this, arguments) + } +} -process.nextTick = wrapWithActivateUvLoop(process.nextTick); +process.nextTick = wrapWithActivateUvLoop(process.nextTick) -global.setImmediate = wrapWithActivateUvLoop(timers.setImmediate); +global.setImmediate = wrapWithActivateUvLoop(timers.setImmediate) -global.clearImmediate = timers.clearImmediate; +global.clearImmediate = timers.clearImmediate if (process.type === 'browser') { // setTimeout needs to update the polling timeout of the event loop, when // called under Chromium's event loop the node's event loop won't get a chance // to update the timeout, so we have to force the node's event loop to // recalculate the timeout in browser process. - global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout); - global.setInterval = wrapWithActivateUvLoop(timers.setInterval); + global.setTimeout = wrapWithActivateUvLoop(timers.setTimeout) + global.setInterval = wrapWithActivateUvLoop(timers.setInterval) } diff --git a/lib/common/reset-search-paths.js b/lib/common/reset-search-paths.js index abf671196735..30709b56a78c 100644 --- a/lib/common/reset-search-paths.js +++ b/lib/common/reset-search-paths.js @@ -1,36 +1,36 @@ -const path = require('path'); -const Module = require('module'); +const path = require('path') +const Module = require('module') // Clear Node's global search paths. -Module.globalPaths.length = 0; +Module.globalPaths.length = 0 // Clear current and parent(init.coffee)'s search paths. -module.paths = []; +module.paths = [] -module.parent.paths = []; +module.parent.paths = [] // Prevent Node from adding paths outside this app to search paths. -Module._nodeModulePaths = function(from) { - var dir, i, part, parts, paths, skipOutsidePaths, splitRe, tip; - from = path.resolve(from); +Module._nodeModulePaths = function (from) { + var dir, i, part, parts, paths, skipOutsidePaths, splitRe, tip + from = path.resolve(from) // If "from" is outside the app then we do nothing. - skipOutsidePaths = from.startsWith(process.resourcesPath); + skipOutsidePaths = from.startsWith(process.resourcesPath) // Following logoic is copied from module.js. - splitRe = process.platform === 'win32' ? /[\/\\]/ : /\//; - paths = []; - parts = from.split(splitRe); + splitRe = process.platform === 'win32' ? /[\/\\]/ : /\// + paths = [] + parts = from.split(splitRe) for (tip = i = parts.length - 1; i >= 0; tip = i += -1) { - part = parts[tip]; + part = parts[tip] if (part === 'node_modules') { - continue; + continue } - dir = parts.slice(0, tip + 1).join(path.sep); + dir = parts.slice(0, tip + 1).join(path.sep) if (skipOutsidePaths && !dir.startsWith(process.resourcesPath)) { - break; + break } - paths.push(path.join(dir, 'node_modules')); + paths.push(path.join(dir, 'node_modules')) } - return paths; -}; + return paths +} diff --git a/lib/renderer/api/desktop-capturer.js b/lib/renderer/api/desktop-capturer.js index 8912deea3a8f..5683e9cff250 100644 --- a/lib/renderer/api/desktop-capturer.js +++ b/lib/renderer/api/desktop-capturer.js @@ -1,47 +1,47 @@ -const ipcRenderer = require('electron').ipcRenderer; -const nativeImage = require('electron').nativeImage; +const ipcRenderer = require('electron').ipcRenderer +const nativeImage = require('electron').nativeImage -var nextId = 0; -var includes = [].includes; +var nextId = 0 +var includes = [].includes -var getNextId = function() { - return ++nextId; -}; +var getNextId = function () { + return ++nextId +} // |options.type| can not be empty and has to include 'window' or 'screen'. -var isValid = function(options) { - return ((options != null ? options.types : void 0) != null) && Array.isArray(options.types); -}; +var isValid = function (options) { + return ((options != null ? options.types : void 0) != null) && Array.isArray(options.types) +} -exports.getSources = function(options, callback) { - var captureScreen, captureWindow, id; +exports.getSources = function (options, callback) { + var captureScreen, captureWindow, id if (!isValid(options)) { - return callback(new Error('Invalid options')); + return callback(new Error('Invalid options')) } - captureWindow = includes.call(options.types, 'window'); - captureScreen = includes.call(options.types, 'screen'); + captureWindow = includes.call(options.types, 'window') + captureScreen = includes.call(options.types, 'screen') if (options.thumbnailSize == null) { options.thumbnailSize = { width: 150, height: 150 - }; + } } - id = getNextId(); - ipcRenderer.send('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', captureWindow, captureScreen, options.thumbnailSize, id); - return ipcRenderer.once("ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_" + id, function(event, sources) { - var source; - return callback(null, (function() { - var i, len, results; - results = []; + id = getNextId() + ipcRenderer.send('ATOM_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', captureWindow, captureScreen, options.thumbnailSize, id) + return ipcRenderer.once('ATOM_RENDERER_DESKTOP_CAPTURER_RESULT_' + id, function (event, sources) { + var source + return callback(null, (function () { + var i, len, results + results = [] for (i = 0, len = sources.length; i < len; i++) { - source = sources[i]; + source = sources[i] results.push({ id: source.id, name: source.name, thumbnail: nativeImage.createFromDataURL(source.thumbnail) - }); + }) } - return results; - })()); - }); -}; + return results + })()) + }) +} diff --git a/lib/renderer/api/exports/electron.js b/lib/renderer/api/exports/electron.js index 34a498fcc065..8e05adc980c4 100644 --- a/lib/renderer/api/exports/electron.js +++ b/lib/renderer/api/exports/electron.js @@ -1,38 +1,38 @@ -const common = require('../../../common/api/exports/electron'); +const common = require('../../../common/api/exports/electron') // Import common modules. -common.defineProperties(exports); +common.defineProperties(exports) Object.defineProperties(exports, { // Renderer side modules, please sort with alphabet order. desktopCapturer: { enumerable: true, - get: function() { - return require('../desktop-capturer'); + get: function () { + return require('../desktop-capturer') } }, ipcRenderer: { enumerable: true, - get: function() { - return require('../ipc-renderer'); + get: function () { + return require('../ipc-renderer') } }, remote: { enumerable: true, - get: function() { - return require('../remote'); + get: function () { + return require('../remote') } }, screen: { enumerable: true, - get: function() { - return require('../screen'); + get: function () { + return require('../screen') } }, webFrame: { enumerable: true, - get: function() { - return require('../web-frame'); + get: function () { + return require('../web-frame') } } -}); +}) diff --git a/lib/renderer/api/ipc-renderer.js b/lib/renderer/api/ipc-renderer.js index 03fef36bec7d..a6b6b1851ea3 100644 --- a/lib/renderer/api/ipc-renderer.js +++ b/lib/renderer/api/ipc-renderer.js @@ -1,21 +1,21 @@ -'use strict'; +'use strict' -const binding = process.atomBinding('ipc'); -const v8Util = process.atomBinding('v8_util'); +const binding = process.atomBinding('ipc') +const v8Util = process.atomBinding('v8_util') // Created by init.js. -const ipcRenderer = v8Util.getHiddenValue(global, 'ipc'); +const ipcRenderer = v8Util.getHiddenValue(global, 'ipc') -ipcRenderer.send = function(...args) { - return binding.send('ipc-message', args); -}; +ipcRenderer.send = function (...args) { + return binding.send('ipc-message', args) +} -ipcRenderer.sendSync = function(...args) { - return JSON.parse(binding.sendSync('ipc-message-sync', args)); -}; +ipcRenderer.sendSync = function (...args) { + return JSON.parse(binding.sendSync('ipc-message-sync', args)) +} -ipcRenderer.sendToHost = function(...args) { - return binding.send('ipc-message-host', args); -}; +ipcRenderer.sendToHost = function (...args) { + return binding.send('ipc-message-host', args) +} -module.exports = ipcRenderer; +module.exports = ipcRenderer diff --git a/lib/renderer/api/ipc.js b/lib/renderer/api/ipc.js index d3e21db2a3af..bda68f7bedbb 100644 --- a/lib/renderer/api/ipc.js +++ b/lib/renderer/api/ipc.js @@ -1,27 +1,27 @@ -const ipcRenderer = require('electron').ipcRenderer; -const deprecate = require('electron').deprecate; -const EventEmitter = require('events').EventEmitter; +const ipcRenderer = require('electron').ipcRenderer +const deprecate = require('electron').deprecate +const EventEmitter = require('events').EventEmitter // This module is deprecated, we mirror everything from ipcRenderer. -deprecate.warn('ipc module', 'require("electron").ipcRenderer'); +deprecate.warn('ipc module', 'require("electron").ipcRenderer') // Routes events of ipcRenderer. -var ipc = new EventEmitter; +var ipc = new EventEmitter -ipcRenderer.emit = function(channel, event, ...args) { - ipc.emit.apply(ipc, [channel].concat(args)); - return EventEmitter.prototype.emit.apply(ipcRenderer, arguments); -}; +ipcRenderer.emit = function (channel, event, ...args) { + ipc.emit.apply(ipc, [channel].concat(args)) + return EventEmitter.prototype.emit.apply(ipcRenderer, arguments) +} // Deprecated. for (var method in ipcRenderer) { if (method.startsWith('send')) { - ipc[method] = ipcRenderer[method]; + ipc[method] = ipcRenderer[method] } } -deprecate.rename(ipc, 'sendChannel', 'send'); +deprecate.rename(ipc, 'sendChannel', 'send') -deprecate.rename(ipc, 'sendChannelSync', 'sendSync'); +deprecate.rename(ipc, 'sendChannelSync', 'sendSync') -module.exports = ipc; +module.exports = ipc diff --git a/lib/renderer/api/remote.js b/lib/renderer/api/remote.js index 6bf7b4229ee3..0028a6191cd0 100644 --- a/lib/renderer/api/remote.js +++ b/lib/renderer/api/remote.js @@ -1,306 +1,306 @@ -'use strict'; +'use strict' -const ipcRenderer = require('electron').ipcRenderer; -const CallbacksRegistry = require('electron').CallbacksRegistry; -const v8Util = process.atomBinding('v8_util'); -const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap; +const ipcRenderer = require('electron').ipcRenderer +const CallbacksRegistry = require('electron').CallbacksRegistry +const v8Util = process.atomBinding('v8_util') +const IDWeakMap = process.atomBinding('id_weak_map').IDWeakMap -const callbacksRegistry = new CallbacksRegistry; +const callbacksRegistry = new CallbacksRegistry -var includes = [].includes; +var includes = [].includes -var remoteObjectCache = new IDWeakMap; +var remoteObjectCache = new IDWeakMap // Check for circular reference. -var isCircular = function(field, visited) { +var isCircular = function (field, visited) { if (typeof field === 'object') { if (includes.call(visited, field)) { - return true; + return true } - visited.push(field); + visited.push(field) } - return false; -}; + return false +} // Convert the arguments object into an array of meta data. -var wrapArgs = function(args, visited) { - var valueToMeta; +var wrapArgs = function (args, visited) { + var valueToMeta if (visited == null) { - visited = []; + visited = [] } - valueToMeta = function(value) { - var field, prop, ret; + valueToMeta = function (value) { + var field, prop, ret if (Array.isArray(value)) { return { type: 'array', value: wrapArgs(value, visited) - }; + } } else if (Buffer.isBuffer(value)) { return { type: 'buffer', value: Array.prototype.slice.call(value, 0) - }; + } } else if (value instanceof Date) { return { type: 'date', value: value.getTime() - }; + } } else if ((value != null ? value.constructor.name : void 0) === 'Promise') { return { type: 'promise', - then: valueToMeta(function(v) { value.then(v); }) - }; + then: valueToMeta(function (v) { value.then(v); }) + } } else if ((value != null) && typeof value === 'object' && v8Util.getHiddenValue(value, 'atomId')) { return { type: 'remote-object', id: v8Util.getHiddenValue(value, 'atomId') - }; + } } else if ((value != null) && typeof value === 'object') { ret = { type: 'object', name: value.constructor.name, members: [] - }; + } for (prop in value) { - field = value[prop]; + field = value[prop] ret.members.push({ name: prop, value: valueToMeta(isCircular(field, visited) ? null : field) - }); + }) } - return ret; + return ret } else if (typeof value === 'function' && v8Util.getHiddenValue(value, 'returnValue')) { return { type: 'function-with-return-value', value: valueToMeta(value()) - }; + } } else if (typeof value === 'function') { return { type: 'function', id: callbacksRegistry.add(value), location: v8Util.getHiddenValue(value, 'location') - }; + } } else { return { type: 'value', value: value - }; + } } - }; - return Array.prototype.slice.call(args).map(valueToMeta); -}; + } + return Array.prototype.slice.call(args).map(valueToMeta) +} // Populate object's members from descriptors. // This matches |getObjectMemebers| in rpc-server. -let setObjectMembers = function(object, metaId, members) { +let setObjectMembers = function (object, metaId, members) { for (let member of members) { if (object.hasOwnProperty(member.name)) - continue; + continue - let descriptor = { enumerable: member.enumerable }; + let descriptor = { enumerable: member.enumerable } if (member.type === 'method') { - let remoteMemberFunction = function() { + let remoteMemberFunction = function () { if (this && this.constructor === remoteMemberFunction) { // Constructor call. - let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, member.name, wrapArgs(arguments)); - return metaToValue(ret); + let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CONSTRUCTOR', metaId, member.name, wrapArgs(arguments)) + return metaToValue(ret) } else { // Call member function. - let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, member.name, wrapArgs(arguments)); - return metaToValue(ret); + let ret = ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_CALL', metaId, member.name, wrapArgs(arguments)) + return metaToValue(ret) } - }; - descriptor.writable = true; - descriptor.configurable = true; - descriptor.value = remoteMemberFunction; + } + descriptor.writable = true + descriptor.configurable = true + descriptor.value = remoteMemberFunction } else if (member.type === 'get') { - descriptor.get = function() { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, member.name)); - }; + descriptor.get = function () { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_GET', metaId, member.name)) + } // Only set setter when it is writable. if (member.writable) { - descriptor.set = function(value) { - ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, member.name, value); - return value; - }; + descriptor.set = function (value) { + ipcRenderer.sendSync('ATOM_BROWSER_MEMBER_SET', metaId, member.name, value) + return value + } } } - Object.defineProperty(object, member.name, descriptor); + Object.defineProperty(object, member.name, descriptor) } -}; +} // Populate object's prototype from descriptor. // This matches |getObjectPrototype| in rpc-server. -let setObjectPrototype = function(object, metaId, descriptor) { +let setObjectPrototype = function (object, metaId, descriptor) { if (descriptor === null) - return; - let proto = {}; - setObjectMembers(proto, metaId, descriptor.members); - setObjectPrototype(proto, metaId, descriptor.proto); - Object.setPrototypeOf(object, proto); -}; + return + let proto = {} + setObjectMembers(proto, metaId, descriptor.members) + setObjectPrototype(proto, metaId, descriptor.proto) + Object.setPrototypeOf(object, proto) +} // Convert meta data from browser into real value. -let metaToValue = function(meta) { - var el, i, len, ref1, results, ret; +let metaToValue = function (meta) { + var el, i, len, ref1, results, ret switch (meta.type) { case 'value': - return meta.value; + return meta.value case 'array': - ref1 = meta.members; - results = []; + ref1 = meta.members + results = [] for (i = 0, len = ref1.length; i < len; i++) { - el = ref1[i]; - results.push(metaToValue(el)); + el = ref1[i] + results.push(metaToValue(el)) } - return results; + return results case 'buffer': - return new Buffer(meta.value); + return new Buffer(meta.value) case 'promise': return Promise.resolve({ then: metaToValue(meta.then) - }); + }) case 'error': - return metaToPlainObject(meta); + return metaToPlainObject(meta) case 'date': - return new Date(meta.value); + return new Date(meta.value) case 'exception': - throw new Error(meta.message + "\n" + meta.stack); + throw new Error(meta.message + '\n' + meta.stack) default: if (remoteObjectCache.has(meta.id)) - return remoteObjectCache.get(meta.id); + return remoteObjectCache.get(meta.id) if (meta.type === 'function') { // A shadow class to represent the remote function object. - let remoteFunction = function() { + let remoteFunction = function () { if (this && this.constructor === remoteFunction) { // Constructor call. - let obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)); + let obj = ipcRenderer.sendSync('ATOM_BROWSER_CONSTRUCTOR', meta.id, wrapArgs(arguments)) // Returning object in constructor will replace constructed object // with the returned object. // http://stackoverflow.com/questions/1978049/what-values-can-a-constructor-return-to-avoid-returning-this - return metaToValue(obj); + return metaToValue(obj) } else { // Function call. - let obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)); - return metaToValue(obj); + let obj = ipcRenderer.sendSync('ATOM_BROWSER_FUNCTION_CALL', meta.id, wrapArgs(arguments)) + return metaToValue(obj) } - }; - ret = remoteFunction; + } + ret = remoteFunction } else { - ret = {}; + ret = {} } // Populate delegate members. - setObjectMembers(ret, meta.id, meta.members); + setObjectMembers(ret, meta.id, meta.members) // Populate delegate prototype. - setObjectPrototype(ret, meta.id, meta.proto); + setObjectPrototype(ret, meta.id, meta.proto) // Set constructor.name to object's name. - Object.defineProperty(ret.constructor, 'name', { value: meta.name }); + Object.defineProperty(ret.constructor, 'name', { value: meta.name }) // Track delegate object's life time, and tell the browser to clean up // when the object is GCed. - v8Util.setDestructor(ret, function() { - ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id); - }); + v8Util.setDestructor(ret, function () { + ipcRenderer.send('ATOM_BROWSER_DEREFERENCE', meta.id) + }) // Remember object's id. - v8Util.setHiddenValue(ret, 'atomId', meta.id); - remoteObjectCache.set(meta.id, ret); - return ret; + v8Util.setHiddenValue(ret, 'atomId', meta.id) + remoteObjectCache.set(meta.id, ret) + return ret } -}; +} // Construct a plain object from the meta. -var metaToPlainObject = function(meta) { - var i, len, obj, ref1; - obj = (function() { +var metaToPlainObject = function (meta) { + var i, len, obj, ref1 + obj = (function () { switch (meta.type) { case 'error': - return new Error; + return new Error default: - return {}; + return {} } - })(); - ref1 = meta.members; + })() + ref1 = meta.members for (i = 0, len = ref1.length; i < len; i++) { - let {name, value} = ref1[i]; - obj[name] = value; + let {name, value} = ref1[i] + obj[name] = value } - return obj; -}; + return obj +} // Browser calls a callback in renderer. -ipcRenderer.on('ATOM_RENDERER_CALLBACK', function(event, id, args) { - return callbacksRegistry.apply(id, metaToValue(args)); -}); +ipcRenderer.on('ATOM_RENDERER_CALLBACK', function (event, id, args) { + return callbacksRegistry.apply(id, metaToValue(args)) +}) // A callback in browser is released. -ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function(event, id) { - return callbacksRegistry.remove(id); -}); +ipcRenderer.on('ATOM_RENDERER_RELEASE_CALLBACK', function (event, id) { + return callbacksRegistry.remove(id) +}) // List all built-in modules in browser process. -const browserModules = require('../../browser/api/exports/electron'); +const browserModules = require('../../browser/api/exports/electron') // And add a helper receiver for each one. -var fn = function(name) { +var fn = function (name) { return Object.defineProperty(exports, name, { - get: function() { - return exports.getBuiltin(name); + get: function () { + return exports.getBuiltin(name) } - }); -}; + }) +} for (var name in browserModules) { - fn(name); + fn(name) } // Get remote module. -exports.require = function(module) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_REQUIRE', module)); -}; +exports.require = function (module) { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_REQUIRE', module)) +} // Alias to remote.require('electron').xxx. -exports.getBuiltin = function(module) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GET_BUILTIN', module)); -}; +exports.getBuiltin = function (module) { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GET_BUILTIN', module)) +} // Get current BrowserWindow. -exports.getCurrentWindow = function() { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WINDOW')); -}; +exports.getCurrentWindow = function () { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WINDOW')) +} // Get current WebContents object. -exports.getCurrentWebContents = function() { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WEB_CONTENTS')); -}; +exports.getCurrentWebContents = function () { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_CURRENT_WEB_CONTENTS')) +} // Get a global object in browser. -exports.getGlobal = function(name) { - return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name)); -}; +exports.getGlobal = function (name) { + return metaToValue(ipcRenderer.sendSync('ATOM_BROWSER_GLOBAL', name)) +} // Get the process object in browser. -exports.__defineGetter__('process', function() { - return exports.getGlobal('process'); -}); +exports.__defineGetter__('process', function () { + return exports.getGlobal('process') +}) // Create a funtion that will return the specifed value when called in browser. -exports.createFunctionWithReturnValue = function(returnValue) { - var func; - func = function() { - return returnValue; - }; - v8Util.setHiddenValue(func, 'returnValue', true); - return func; -}; +exports.createFunctionWithReturnValue = function (returnValue) { + var func + func = function () { + return returnValue + } + v8Util.setHiddenValue(func, 'returnValue', true) + return func +} // Get the guest WebContents from guestInstanceId. -exports.getGuestWebContents = function(guestInstanceId) { - var meta; - meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId); - return metaToValue(meta); -}; +exports.getGuestWebContents = function (guestInstanceId) { + var meta + meta = ipcRenderer.sendSync('ATOM_BROWSER_GUEST_WEB_CONTENTS', guestInstanceId) + return metaToValue(meta) +} diff --git a/lib/renderer/api/screen.js b/lib/renderer/api/screen.js index fb74d78f79d2..9eecd49dc5bf 100644 --- a/lib/renderer/api/screen.js +++ b/lib/renderer/api/screen.js @@ -1 +1 @@ -module.exports = require('electron').remote.screen; +module.exports = require('electron').remote.screen diff --git a/lib/renderer/api/web-frame.js b/lib/renderer/api/web-frame.js index 8ae35d7b8ac6..7f48f1eabbd1 100644 --- a/lib/renderer/api/web-frame.js +++ b/lib/renderer/api/web-frame.js @@ -1,19 +1,19 @@ -'use strict'; +'use strict' -const deprecate = require('electron').deprecate; -const EventEmitter = require('events').EventEmitter; +const deprecate = require('electron').deprecate +const EventEmitter = require('events').EventEmitter -const webFrame = process.atomBinding('web_frame').webFrame; +const webFrame = process.atomBinding('web_frame').webFrame // webFrame is an EventEmitter. -webFrame.__proto__ = EventEmitter.prototype; +webFrame.__proto__ = EventEmitter.prototype // Lots of webview would subscribe to webFrame's events. -webFrame.setMaxListeners(0); +webFrame.setMaxListeners(0) // Deprecated. -deprecate.rename(webFrame, 'registerUrlSchemeAsSecure', 'registerURLSchemeAsSecure'); -deprecate.rename(webFrame, 'registerUrlSchemeAsBypassingCSP', 'registerURLSchemeAsBypassingCSP'); -deprecate.rename(webFrame, 'registerUrlSchemeAsPrivileged', 'registerURLSchemeAsPrivileged'); +deprecate.rename(webFrame, 'registerUrlSchemeAsSecure', 'registerURLSchemeAsSecure') +deprecate.rename(webFrame, 'registerUrlSchemeAsBypassingCSP', 'registerURLSchemeAsBypassingCSP') +deprecate.rename(webFrame, 'registerUrlSchemeAsPrivileged', 'registerURLSchemeAsPrivileged') -module.exports = webFrame; +module.exports = webFrame diff --git a/lib/renderer/chrome-api.js b/lib/renderer/chrome-api.js index 7ff7d2e87b99..eca791057c3c 100644 --- a/lib/renderer/chrome-api.js +++ b/lib/renderer/chrome-api.js @@ -1,13 +1,13 @@ -const url = require('url'); -const chrome = window.chrome = window.chrome || {}; +const url = require('url') +const chrome = window.chrome = window.chrome || {} chrome.extension = { - getURL: function(path) { + getURL: function (path) { return url.format({ protocol: location.protocol, slashes: true, hostname: location.hostname, pathname: path - }); + }) } -}; +} diff --git a/lib/renderer/init.js b/lib/renderer/init.js index 45ea2d45654e..511f9e57e8f7 100644 --- a/lib/renderer/init.js +++ b/lib/renderer/init.js @@ -1,139 +1,139 @@ -'use strict'; +'use strict' -const events = require('events'); -const path = require('path'); -const Module = require('module'); +const events = require('events') +const path = require('path') +const Module = require('module') // We modified the original process.argv to let node.js load the // atom-renderer.js, we need to restore it here. -process.argv.splice(1, 1); +process.argv.splice(1, 1) // Clear search paths. -require('../common/reset-search-paths'); +require('../common/reset-search-paths') // Import common settings. -require('../common/init'); +require('../common/init') -var globalPaths = Module.globalPaths; +var globalPaths = Module.globalPaths if (!process.env.ELECTRON_HIDE_INTERNAL_MODULES) { - globalPaths.push(path.join(__dirname, 'api')); + globalPaths.push(path.join(__dirname, 'api')) } // Expose public APIs. -globalPaths.push(path.join(__dirname, 'api', 'exports')); +globalPaths.push(path.join(__dirname, 'api', 'exports')) // The global variable will be used by ipc for event dispatching -var v8Util = process.atomBinding('v8_util'); +var v8Util = process.atomBinding('v8_util') -v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter); +v8Util.setHiddenValue(global, 'ipc', new events.EventEmitter) // Use electron module after everything is ready. -const electron = require('electron'); +const electron = require('electron') // Call webFrame method. electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_WEB_FRAME_METHOD', (event, method, args) => { - electron.webFrame[method].apply(electron.webFrame, args); -}); + electron.webFrame[method].apply(electron.webFrame, args) +}) electron.ipcRenderer.on('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', (event, requestId, method, args) => { - const responseCallback = function(result) { - event.sender.send(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, result); - }; - args.push(responseCallback); - electron.webFrame[method].apply(electron.webFrame, args); -}); + const responseCallback = function (result) { + event.sender.send(`ELECTRON_INTERNAL_BROWSER_ASYNC_WEB_FRAME_RESPONSE_${requestId}`, result) + } + args.push(responseCallback) + electron.webFrame[method].apply(electron.webFrame, args) +}) // Process command line arguments. -var nodeIntegration = 'false'; -var preloadScript = null; +var nodeIntegration = 'false' +var preloadScript = null -var ref = process.argv; -var i, len, arg; +var ref = process.argv +var i, len, arg for (i = 0, len = ref.length; i < len; i++) { - arg = ref[i]; + arg = ref[i] if (arg.indexOf('--guest-instance-id=') === 0) { // This is a guest web view. - process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1)); + process.guestInstanceId = parseInt(arg.substr(arg.indexOf('=') + 1)) } else if (arg.indexOf('--opener-id=') === 0) { // This is a guest BrowserWindow. - process.openerId = parseInt(arg.substr(arg.indexOf('=') + 1)); + process.openerId = parseInt(arg.substr(arg.indexOf('=') + 1)) } else if (arg.indexOf('--node-integration=') === 0) { - nodeIntegration = arg.substr(arg.indexOf('=') + 1); + nodeIntegration = arg.substr(arg.indexOf('=') + 1) } else if (arg.indexOf('--preload=') === 0) { - preloadScript = arg.substr(arg.indexOf('=') + 1); + preloadScript = arg.substr(arg.indexOf('=') + 1) } } if (location.protocol === 'chrome-devtools:') { // Override some inspector APIs. - require('./inspector'); - nodeIntegration = 'true'; + require('./inspector') + nodeIntegration = 'true' } else if (location.protocol === 'chrome-extension:') { // Add implementations of chrome API. - require('./chrome-api'); - nodeIntegration = 'true'; + require('./chrome-api') + nodeIntegration = 'true' } else { // Override default web functions. - require('./override'); + require('./override') // Load webview tag implementation. if (process.guestInstanceId == null) { - require('./web-view/web-view'); - require('./web-view/web-view-attributes'); + require('./web-view/web-view') + require('./web-view/web-view-attributes') } } if (nodeIntegration === 'true' || nodeIntegration === 'all' || nodeIntegration === 'except-iframe' || nodeIntegration === 'manual-enable-iframe') { // Export node bindings to global. - global.require = require; - global.module = module; + global.require = require + global.module = module // Set the __filename to the path of html file if it is file: protocol. if (window.location.protocol === 'file:') { - var pathname = process.platform === 'win32' && window.location.pathname[0] === '/' ? window.location.pathname.substr(1) : window.location.pathname; - global.__filename = path.normalize(decodeURIComponent(pathname)); - global.__dirname = path.dirname(global.__filename); + var pathname = process.platform === 'win32' && window.location.pathname[0] === '/' ? window.location.pathname.substr(1) : window.location.pathname + global.__filename = path.normalize(decodeURIComponent(pathname)) + global.__dirname = path.dirname(global.__filename) // Set module's filename so relative require can work as expected. - module.filename = global.__filename; + module.filename = global.__filename // Also search for module under the html file. - module.paths = module.paths.concat(Module._nodeModulePaths(global.__dirname)); + module.paths = module.paths.concat(Module._nodeModulePaths(global.__dirname)) } else { - global.__filename = __filename; - global.__dirname = __dirname; + global.__filename = __filename + global.__dirname = __dirname } // Redirect window.onerror to uncaughtException. - window.onerror = function(message, filename, lineno, colno, error) { + window.onerror = function (message, filename, lineno, colno, error) { if (global.process.listeners('uncaughtException').length > 0) { - global.process.emit('uncaughtException', error); - return true; + global.process.emit('uncaughtException', error) + return true } else { - return false; + return false } - }; + } } else { // Delete Node's symbols after the Environment has been loaded. - process.once('loaded', function() { - delete global.process; - delete global.setImmediate; - delete global.clearImmediate; - return delete global.global; - }); + process.once('loaded', function () { + delete global.process + delete global.setImmediate + delete global.clearImmediate + return delete global.global + }) } // Load the script specfied by the "preload" attribute. if (preloadScript) { try { - require(preloadScript); + require(preloadScript) } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { - console.error("Unable to load preload script " + preloadScript); + console.error('Unable to load preload script ' + preloadScript) } else { - console.error(error); - console.error(error.stack); + console.error(error) + console.error(error.stack) } } } diff --git a/lib/renderer/inspector.js b/lib/renderer/inspector.js index d1473c7d1bed..61be586f7887 100644 --- a/lib/renderer/inspector.js +++ b/lib/renderer/inspector.js @@ -1,16 +1,16 @@ -window.onload = function() { +window.onload = function () { // Use menu API to show context menu. - InspectorFrontendHost.showContextMenuAtPoint = createMenu; + InspectorFrontendHost.showContextMenuAtPoint = createMenu // Use dialog API to override file chooser dialog. - return (WebInspector.createFileSelectorElement = createFileSelectorElement); -}; + return (WebInspector.createFileSelectorElement = createFileSelectorElement) +} -var convertToMenuTemplate = function(items) { - var fn, i, item, len, template; - template = []; - fn = function(item) { - var transformed; +var convertToMenuTemplate = function (items) { + var fn, i, item, len, template + template = [] + fn = function (item) { + var transformed transformed = item.type === 'subMenu' ? { type: 'submenu', label: item.label, @@ -27,55 +27,55 @@ var convertToMenuTemplate = function(items) { type: 'normal', label: item.label, enabled: item.enabled - }; - if (item.id != null) { - transformed.click = function() { - DevToolsAPI.contextMenuItemSelected(item.id); - return DevToolsAPI.contextMenuCleared(); - }; } - return template.push(transformed); - }; - for (i = 0, len = items.length; i < len; i++) { - item = items[i]; - fn(item); + if (item.id != null) { + transformed.click = function () { + DevToolsAPI.contextMenuItemSelected(item.id) + return DevToolsAPI.contextMenuCleared() + } + } + return template.push(transformed) } - return template; -}; + for (i = 0, len = items.length; i < len; i++) { + item = items[i] + fn(item) + } + return template +} -var createMenu = function(x, y, items) { - const remote = require('electron').remote; - const Menu = remote.Menu; - const menu = Menu.buildFromTemplate(convertToMenuTemplate(items)); +var createMenu = function (x, y, items) { + const remote = require('electron').remote + const Menu = remote.Menu + const menu = Menu.buildFromTemplate(convertToMenuTemplate(items)) // The menu is expected to show asynchronously. - return setTimeout(function() { - return menu.popup(remote.getCurrentWindow()); - }); -}; + return setTimeout(function () { + return menu.popup(remote.getCurrentWindow()) + }) +} -var showFileChooserDialog = function(callback) { - var dialog, files, remote; - remote = require('electron').remote; - dialog = remote.dialog; - files = dialog.showOpenDialog({}); +var showFileChooserDialog = function (callback) { + var dialog, files, remote + remote = require('electron').remote + dialog = remote.dialog + files = dialog.showOpenDialog({}) if (files != null) { - return callback(pathToHtml5FileObject(files[0])); + return callback(pathToHtml5FileObject(files[0])) } -}; +} -var pathToHtml5FileObject = function(path) { - var blob, fs; - fs = require('fs'); - blob = new Blob([fs.readFileSync(path)]); - blob.name = path; - return blob; -}; +var pathToHtml5FileObject = function (path) { + var blob, fs + fs = require('fs') + blob = new Blob([fs.readFileSync(path)]) + blob.name = path + return blob +} -var createFileSelectorElement = function(callback) { - var fileSelectorElement; - fileSelectorElement = document.createElement('span'); - fileSelectorElement.style.display = 'none'; - fileSelectorElement.click = showFileChooserDialog.bind(this, callback); - return fileSelectorElement; -}; +var createFileSelectorElement = function (callback) { + var fileSelectorElement + fileSelectorElement = document.createElement('span') + fileSelectorElement.style.display = 'none' + fileSelectorElement.click = showFileChooserDialog.bind(this, callback) + return fileSelectorElement +} diff --git a/lib/renderer/override.js b/lib/renderer/override.js index 92019ba1f42f..ddabf793ff77 100644 --- a/lib/renderer/override.js +++ b/lib/renderer/override.js @@ -1,266 +1,265 @@ -'use strict'; +'use strict' -const ipcRenderer = require('electron').ipcRenderer; -const remote = require('electron').remote; +const ipcRenderer = require('electron').ipcRenderer +const remote = require('electron').remote // Cache browser window visibility -var _isVisible = true; -var _isMinimized = false; -(function() { - var currentWindow; - currentWindow = remote.getCurrentWindow(); - _isVisible = currentWindow.isVisible(); - _isMinimized = currentWindow.isMinimized(); -})(); +var _isVisible = true +var _isMinimized = false +;(function () { + var currentWindow + currentWindow = remote.getCurrentWindow() + _isVisible = currentWindow.isVisible() + _isMinimized = currentWindow.isMinimized() +})() // Helper function to resolve relative url. -var a = window.top.document.createElement('a'); +var a = window.top.document.createElement('a') -var resolveURL = function(url) { - a.href = url; - return a.href; -}; +var resolveURL = function (url) { + a.href = url + return a.href +} // Window object returned by "window.open". -var BrowserWindowProxy = (function() { - BrowserWindowProxy.proxies = {}; +var BrowserWindowProxy = (function () { + BrowserWindowProxy.proxies = {} - BrowserWindowProxy.getOrCreate = function(guestId) { - var base; - return (base = this.proxies)[guestId] != null ? base[guestId] : base[guestId] = new BrowserWindowProxy(guestId); - }; - - BrowserWindowProxy.remove = function(guestId) { - return delete this.proxies[guestId]; - }; - - function BrowserWindowProxy(guestId1) { - this.guestId = guestId1; - this.closed = false; - ipcRenderer.once("ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_" + this.guestId, () => { - BrowserWindowProxy.remove(this.guestId); - this.closed = true; - }); + BrowserWindowProxy.getOrCreate = function (guestId) { + var base + return (base = this.proxies)[guestId] != null ? base[guestId] : base[guestId] = new BrowserWindowProxy(guestId) } - BrowserWindowProxy.prototype.close = function() { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', this.guestId); - }; + BrowserWindowProxy.remove = function (guestId) { + return delete this.proxies[guestId] + } - BrowserWindowProxy.prototype.focus = function() { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'focus'); - }; + function BrowserWindowProxy (guestId1) { + this.guestId = guestId1 + this.closed = false + ipcRenderer.once('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSED_' + this.guestId, () => { + BrowserWindowProxy.remove(this.guestId) + this.closed = true + }) + } - BrowserWindowProxy.prototype.blur = function() { - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'blur'); - }; + BrowserWindowProxy.prototype.close = function () { + return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_CLOSE', this.guestId) + } + + BrowserWindowProxy.prototype.focus = function () { + return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'focus') + } + + BrowserWindowProxy.prototype.blur = function () { + return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'blur') + } Object.defineProperty(BrowserWindowProxy.prototype, 'location', { - get: function() { - return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'getURL'); + get: function () { + return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'getURL') }, - set: function(url) { - return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'loadURL', url); + set: function (url) { + return ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_METHOD', this.guestId, 'loadURL', url) } - }); + }) - BrowserWindowProxy.prototype.postMessage = function(message, targetOrigin) { + BrowserWindowProxy.prototype.postMessage = function (message, targetOrigin) { if (targetOrigin == null) { - targetOrigin = '*'; + targetOrigin = '*' } - return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, location.origin); - }; + return ipcRenderer.send('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_POSTMESSAGE', this.guestId, message, targetOrigin, location.origin) + } - BrowserWindowProxy.prototype["eval"] = function(...args) { - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(args)); - }; + BrowserWindowProxy.prototype['eval'] = function (...args) { + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_GUEST_WINDOW_MANAGER_WEB_CONTENTS_METHOD', this.guestId, 'executeJavaScript'].concat(args)) + } - return BrowserWindowProxy; - -})(); + return BrowserWindowProxy +})() if (process.guestInstanceId == null) { // Override default window.close. - window.close = function() { - return remote.getCurrentWindow().close(); - }; + window.close = function () { + return remote.getCurrentWindow().close() + } } // Make the browser window or guest view emit "new-window" event. -window.open = function(url, frameName, features) { - var feature, guestId, i, j, len, len1, name, options, ref1, ref2, value; +window.open = function (url, frameName, features) { + var feature, guestId, i, j, len, len1, name, options, ref1, ref2, value if (frameName == null) { - frameName = ''; + frameName = '' } if (features == null) { - features = ''; + features = '' } - options = {}; + options = {} // TODO remove hyphenated options in both of the following arrays for 1.0 - const ints = ['x', 'y', 'width', 'height', 'min-width', 'minWidth', 'max-width', 'maxWidth', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor']; - const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload']; + const ints = ['x', 'y', 'width', 'height', 'min-width', 'minWidth', 'max-width', 'maxWidth', 'min-height', 'minHeight', 'max-height', 'maxHeight', 'zoom-factor', 'zoomFactor'] + const webPreferences = ['zoom-factor', 'zoomFactor', 'node-integration', 'nodeIntegration', 'preload'] // Make sure to get rid of excessive whitespace in the property name - ref1 = features.split(/,\s*/); + ref1 = features.split(/,\s*/) for (i = 0, len = ref1.length; i < len; i++) { - feature = ref1[i]; - ref2 = feature.split(/\s*=/); - name = ref2[0]; - value = ref2[1]; - value = value === 'yes' || value === '1' ? true : value === 'no' || value === '0' ? false : value; + feature = ref1[i] + ref2 = feature.split(/\s*=/) + name = ref2[0] + value = ref2[1] + value = value === 'yes' || value === '1' ? true : value === 'no' || value === '0' ? false : value if (webPreferences.includes(name)) { if (options.webPreferences == null) { - options.webPreferences = {}; + options.webPreferences = {} } - options.webPreferences[name] = value; + options.webPreferences[name] = value } else { - options[name] = value; + options[name] = value } } if (options.left) { if (options.x == null) { - options.x = options.left; + options.x = options.left } } if (options.top) { if (options.y == null) { - options.y = options.top; + options.y = options.top } } if (options.title == null) { - options.title = frameName; + options.title = frameName } if (options.width == null) { - options.width = 800; + options.width = 800 } if (options.height == null) { - options.height = 600; + options.height = 600 } // Resolve relative urls. - url = resolveURL(url); + url = resolveURL(url) for (j = 0, len1 = ints.length; j < len1; j++) { - name = ints[j]; + name = ints[j] if (options[name] != null) { - options[name] = parseInt(options[name], 10); + options[name] = parseInt(options[name], 10) } } - guestId = ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, options); + guestId = ipcRenderer.sendSync('ATOM_SHELL_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, frameName, options) if (guestId) { - return BrowserWindowProxy.getOrCreate(guestId); + return BrowserWindowProxy.getOrCreate(guestId) } else { - return null; + return null } -}; +} // Use the dialog API to implement alert(). window.alert = function(message, title) { - var buttons; - if (arguments.length == 0) { - message = ''; + var buttons + if (arguments.length === 0) { + message = '' } if (title == null) { - title = ''; + title = '' } - buttons = ['OK']; - message = String(message); + buttons = ['OK'] + message = String(message) remote.dialog.showMessageBox(remote.getCurrentWindow(), { message: message, title: title, buttons: buttons - }); + }) - // Alert should always return undefined. -}; +// Alert should always return undefined. +} // And the confirm(). -window.confirm = function(message, title) { - var buttons, cancelId; +window.confirm = function (message, title) { + var buttons, cancelId if (title == null) { - title = ''; + title = '' } - buttons = ['OK', 'Cancel']; - cancelId = 1; + buttons = ['OK', 'Cancel'] + cancelId = 1 return !remote.dialog.showMessageBox(remote.getCurrentWindow(), { message: message, title: title, buttons: buttons, cancelId: cancelId - }); -}; + }) +} // But we do not support prompt(). -window.prompt = function() { - throw new Error('prompt() is and will not be supported.'); -}; +window.prompt = function () { + throw new Error('prompt() is and will not be supported.') +} if (process.openerId != null) { - window.opener = BrowserWindowProxy.getOrCreate(process.openerId); + window.opener = BrowserWindowProxy.getOrCreate(process.openerId) } ipcRenderer.on('ATOM_RENDERER_WINDOW_VISIBILITY_CHANGE', function (event, isVisible, isMinimized) { - var hasChanged = _isVisible != isVisible || _isMinimized != isMinimized; + var hasChanged = _isVisible != isVisible || _isMinimized != isMinimized if (hasChanged) { - _isVisible = isVisible; - _isMinimized = isMinimized; + _isVisible = isVisible + _isMinimized = isMinimized - document.dispatchEvent(new Event('visibilitychange')); + document.dispatchEvent(new Event('visibilitychange')) } -}); +}) -ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function(event, sourceId, message, sourceOrigin) { +ipcRenderer.on('ATOM_SHELL_GUEST_WINDOW_POSTMESSAGE', function (event, sourceId, message, sourceOrigin) { // Manually dispatch event instead of using postMessage because we also need to // set event.source. - event = document.createEvent('Event'); - event.initEvent('message', false, false); - event.data = message; - event.origin = sourceOrigin; - event.source = BrowserWindowProxy.getOrCreate(sourceId); - return window.dispatchEvent(event); -}); + event = document.createEvent('Event') + event.initEvent('message', false, false) + event.data = message + event.origin = sourceOrigin + event.source = BrowserWindowProxy.getOrCreate(sourceId) + return window.dispatchEvent(event) +}) // Forward history operations to browser. -var sendHistoryOperation = function(...args) { - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_NAVIGATION_CONTROLLER'].concat(args)); -}; +var sendHistoryOperation = function (...args) { + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_SHELL_NAVIGATION_CONTROLLER'].concat(args)) +} -var getHistoryOperation = function(...args) { - return ipcRenderer.sendSync.apply(ipcRenderer, ['ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER'].concat(args)); -}; +var getHistoryOperation = function (...args) { + return ipcRenderer.sendSync.apply(ipcRenderer, ['ATOM_SHELL_SYNC_NAVIGATION_CONTROLLER'].concat(args)) +} -window.history.back = function() { - return sendHistoryOperation('goBack'); -}; +window.history.back = function () { + return sendHistoryOperation('goBack') +} -window.history.forward = function() { - return sendHistoryOperation('goForward'); -}; +window.history.forward = function () { + return sendHistoryOperation('goForward') +} -window.history.go = function(offset) { - return sendHistoryOperation('goToOffset', offset); -}; +window.history.go = function (offset) { + return sendHistoryOperation('goToOffset', offset) +} Object.defineProperty(window.history, 'length', { - get: function() { - return getHistoryOperation('length'); + get: function () { + return getHistoryOperation('length') } -}); +}) // Make document.hidden and document.visibilityState return the correct value. Object.defineProperty(document, 'hidden', { get: function () { - return _isMinimized || !_isVisible; + return _isMinimized || !_isVisible } -}); +}) Object.defineProperty(document, 'visibilityState', { - get: function() { + get: function () { if (_isVisible && !_isMinimized) { - return "visible"; + return 'visible' } else { - return "hidden"; + return 'hidden' } } -}); +}) diff --git a/lib/renderer/web-view/guest-view-internal.js b/lib/renderer/web-view/guest-view-internal.js index a4d8930d904b..48ddf5ea10bc 100644 --- a/lib/renderer/web-view/guest-view-internal.js +++ b/lib/renderer/web-view/guest-view-internal.js @@ -1,9 +1,9 @@ -'use strict'; +'use strict' -const ipcRenderer = require('electron').ipcRenderer; -const webFrame = require('electron').webFrame; +const ipcRenderer = require('electron').ipcRenderer +const webFrame = require('electron').webFrame -var requestId= 0; +var requestId = 0 var WEB_VIEW_EVENTS = { 'load-commit': ['url', 'isMainFrame'], @@ -36,71 +36,71 @@ var WEB_VIEW_EVENTS = { 'enter-html-full-screen': [], 'leave-html-full-screen': [], 'found-in-page': ['result'] -}; +} var DEPRECATED_EVENTS = { 'page-title-updated': 'page-title-set' -}; +} -var dispatchEvent = function(webView, eventName, eventKey, ...args) { - var domEvent, f, i, j, len, ref1; +var dispatchEvent = function (webView, eventName, eventKey, ...args) { + var domEvent, f, i, j, len, ref1 if (DEPRECATED_EVENTS[eventName] != null) { - dispatchEvent.apply(null, [webView, DEPRECATED_EVENTS[eventName], eventKey].concat(args)); + dispatchEvent.apply(null, [webView, DEPRECATED_EVENTS[eventName], eventKey].concat(args)) } - domEvent = new Event(eventName); - ref1 = WEB_VIEW_EVENTS[eventKey]; + domEvent = new Event(eventName) + ref1 = WEB_VIEW_EVENTS[eventKey] for (i = j = 0, len = ref1.length; j < len; i = ++j) { - f = ref1[i]; - domEvent[f] = args[i]; + f = ref1[i] + domEvent[f] = args[i] } - webView.dispatchEvent(domEvent); + webView.dispatchEvent(domEvent) if (eventName === 'load-commit') { - return webView.onLoadCommit(domEvent); + return webView.onLoadCommit(domEvent) } -}; +} module.exports = { - registerEvents: function(webView, viewInstanceId) { - ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + viewInstanceId, function(event, eventName, ...args) { - return dispatchEvent.apply(null, [webView, eventName, eventName].concat(args)); - }); + registerEvents: function (webView, viewInstanceId) { + ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId, function (event, eventName, ...args) { + return dispatchEvent.apply(null, [webView, eventName, eventName].concat(args)) + }) - ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + viewInstanceId, function(event, channel, ...args) { - var domEvent = new Event('ipc-message'); - domEvent.channel = channel; - domEvent.args = args; - return webView.dispatchEvent(domEvent); - }); + ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId, function (event, channel, ...args) { + var domEvent = new Event('ipc-message') + domEvent.channel = channel + domEvent.args = args + return webView.dispatchEvent(domEvent) + }) - return ipcRenderer.on("ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + viewInstanceId, function(event, ...args) { - var domEvent, f, i, j, len, ref1; - domEvent = new Event('size-changed'); - ref1 = ['oldWidth', 'oldHeight', 'newWidth', 'newHeight']; + return ipcRenderer.on('ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId, function (event, ...args) { + var domEvent, f, i, j, len, ref1 + domEvent = new Event('size-changed') + ref1 = ['oldWidth', 'oldHeight', 'newWidth', 'newHeight'] for (i = j = 0, len = ref1.length; j < len; i = ++j) { - f = ref1[i]; - domEvent[f] = args[i]; + f = ref1[i] + domEvent[f] = args[i] } - return webView.onSizeChanged(domEvent); - }); + return webView.onSizeChanged(domEvent) + }) }, - deregisterEvents: function(viewInstanceId) { - ipcRenderer.removeAllListeners("ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-" + viewInstanceId); - ipcRenderer.removeAllListeners("ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-" + viewInstanceId); - return ipcRenderer.removeAllListeners("ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-" + viewInstanceId); + deregisterEvents: function (viewInstanceId) { + ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_DISPATCH_EVENT-' + viewInstanceId) + ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_IPC_MESSAGE-' + viewInstanceId) + return ipcRenderer.removeAllListeners('ATOM_SHELL_GUEST_VIEW_INTERNAL_SIZE_CHANGED-' + viewInstanceId) }, - createGuest: function(params, callback) { - requestId++; - ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId); - return ipcRenderer.once("ATOM_SHELL_RESPONSE_" + requestId, callback); + createGuest: function (params, callback) { + requestId++ + ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_CREATE_GUEST', params, requestId) + return ipcRenderer.once('ATOM_SHELL_RESPONSE_' + requestId, callback) }, - attachGuest: function(elementInstanceId, guestInstanceId, params) { - ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params); - return webFrame.attachGuest(elementInstanceId); + attachGuest: function (elementInstanceId, guestInstanceId, params) { + ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_ATTACH_GUEST', elementInstanceId, guestInstanceId, params) + return webFrame.attachGuest(elementInstanceId) }, - destroyGuest: function(guestInstanceId) { - return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId); + destroyGuest: function (guestInstanceId) { + return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_DESTROY_GUEST', guestInstanceId) }, - setSize: function(guestInstanceId, params) { - return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params); + setSize: function (guestInstanceId, params) { + return ipcRenderer.send('ATOM_SHELL_GUEST_VIEW_MANAGER_SET_SIZE', guestInstanceId, params) }, -}; +} diff --git a/lib/renderer/web-view/web-view-attributes.js b/lib/renderer/web-view/web-view-attributes.js index a298f3a96a4e..712973cea85d 100644 --- a/lib/renderer/web-view/web-view-attributes.js +++ b/lib/renderer/web-view/web-view-attributes.js @@ -1,95 +1,95 @@ -'use strict'; +'use strict' -const WebViewImpl = require('./web-view'); -const guestViewInternal = require('./guest-view-internal'); -const webViewConstants = require('./web-view-constants'); -const remote = require('electron').remote; +const WebViewImpl = require('./web-view') +const guestViewInternal = require('./guest-view-internal') +const webViewConstants = require('./web-view-constants') +const remote = require('electron').remote // Helper function to resolve url set in attribute. -var a = document.createElement('a'); +var a = document.createElement('a') -var resolveURL = function(url) { - a.href = url; - return a.href; -}; +var resolveURL = function (url) { + a.href = url + return a.href +} // Attribute objects. // Default implementation of a WebView attribute. class WebViewAttribute { - constructor(name, webViewImpl) { - this.name = name; - this.value = webViewImpl.webviewNode[name] || ''; - this.webViewImpl = webViewImpl; - this.ignoreMutation = false; - this.defineProperty(); + constructor (name, webViewImpl) { + this.name = name + this.value = webViewImpl.webviewNode[name] || '' + this.webViewImpl = webViewImpl + this.ignoreMutation = false + this.defineProperty() } // Retrieves and returns the attribute's value. - getValue() { - return this.webViewImpl.webviewNode.getAttribute(this.name) || this.value; + getValue () { + return this.webViewImpl.webviewNode.getAttribute(this.name) || this.value } // Sets the attribute's value. - setValue(value) { - return this.webViewImpl.webviewNode.setAttribute(this.name, value || ''); + setValue (value) { + return this.webViewImpl.webviewNode.setAttribute(this.name, value || '') } // Changes the attribute's value without triggering its mutation handler. - setValueIgnoreMutation(value) { - this.ignoreMutation = true; - this.setValue(value); - return this.ignoreMutation = false; + setValueIgnoreMutation (value) { + this.ignoreMutation = true + this.setValue(value) + return this.ignoreMutation = false } // Defines this attribute as a property on the webview node. - defineProperty() { + defineProperty () { return Object.defineProperty(this.webViewImpl.webviewNode, this.name, { get: () => { - return this.getValue(); + return this.getValue() }, set: (value) => { - return this.setValue(value); + return this.setValue(value) }, enumerable: true - }); + }) } // Called when the attribute's value changes. - handleMutation() {} + handleMutation () {} } // An attribute that is treated as a Boolean. class BooleanAttribute extends WebViewAttribute { - constructor(name, webViewImpl) { - super(name, webViewImpl); + constructor (name, webViewImpl) { + super(name, webViewImpl) } - getValue() { - return this.webViewImpl.webviewNode.hasAttribute(this.name); + getValue () { + return this.webViewImpl.webviewNode.hasAttribute(this.name) } - setValue(value) { + setValue (value) { if (!value) { - return this.webViewImpl.webviewNode.removeAttribute(this.name); + return this.webViewImpl.webviewNode.removeAttribute(this.name) } else { - return this.webViewImpl.webviewNode.setAttribute(this.name, ''); + return this.webViewImpl.webviewNode.setAttribute(this.name, '') } } } // Attribute used to define the demension limits of autosizing. class AutosizeDimensionAttribute extends WebViewAttribute { - constructor(name, webViewImpl) { - super(name, webViewImpl); + constructor (name, webViewImpl) { + super(name, webViewImpl) } - getValue() { - return parseInt(this.webViewImpl.webviewNode.getAttribute(this.name)) || 0; + getValue () { + return parseInt(this.webViewImpl.webviewNode.getAttribute(this.name)) || 0 } - handleMutation() { + handleMutation () { if (!this.webViewImpl.guestInstanceId) { - return; + return } return guestViewInternal.setSize(this.webViewImpl.guestInstanceId, { enableAutoSize: this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE].getValue(), @@ -101,197 +101,194 @@ class AutosizeDimensionAttribute extends WebViewAttribute { width: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() || 0), height: parseInt(this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() || 0) } - }); + }) } } - // Attribute that specifies whether the webview should be autosized. class AutosizeAttribute extends BooleanAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_AUTOSIZE, webViewImpl); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_AUTOSIZE, webViewImpl) } } -AutosizeAttribute.prototype.handleMutation = AutosizeDimensionAttribute.prototype.handleMutation; +AutosizeAttribute.prototype.handleMutation = AutosizeDimensionAttribute.prototype.handleMutation // Attribute representing the state of the storage partition. class PartitionAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_PARTITION, webViewImpl); - this.validPartitionId = true; + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_PARTITION, webViewImpl) + this.validPartitionId = true } - handleMutation(oldValue, newValue) { - newValue = newValue || ''; + handleMutation (oldValue, newValue) { + newValue = newValue || '' // The partition cannot change if the webview has already navigated. if (!this.webViewImpl.beforeFirstNavigation) { - window.console.error(webViewConstants.ERROR_MSG_ALREADY_NAVIGATED); - this.setValueIgnoreMutation(oldValue); - return; + window.console.error(webViewConstants.ERROR_MSG_ALREADY_NAVIGATED) + this.setValueIgnoreMutation(oldValue) + return } if (newValue === 'persist:') { - this.validPartitionId = false; - return window.console.error(webViewConstants.ERROR_MSG_INVALID_PARTITION_ATTRIBUTE); + this.validPartitionId = false + return window.console.error(webViewConstants.ERROR_MSG_INVALID_PARTITION_ATTRIBUTE) } } } // Attribute that handles the location and navigation of the webview. class SrcAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_SRC, webViewImpl); - this.setupMutationObserver(); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_SRC, webViewImpl) + this.setupMutationObserver() } - getValue() { + getValue () { if (this.webViewImpl.webviewNode.hasAttribute(this.name)) { - return resolveURL(this.webViewImpl.webviewNode.getAttribute(this.name)); + return resolveURL(this.webViewImpl.webviewNode.getAttribute(this.name)) } else { - return this.value; + return this.value } } - setValueIgnoreMutation(value) { - super.setValueIgnoreMutation(value); + setValueIgnoreMutation (value) { + super.setValueIgnoreMutation(value) // takeRecords() is needed to clear queued up src mutations. Without it, it // is possible for this change to get picked up asyncronously by src's // mutation observer |observer|, and then get handled even though we do not // want to handle this mutation. - return this.observer.takeRecords(); + return this.observer.takeRecords() } - handleMutation(oldValue, newValue) { - + handleMutation (oldValue, newValue) { // Once we have navigated, we don't allow clearing the src attribute. // Once enters a navigated state, it cannot return to a // placeholder state. if (!newValue && oldValue) { - // src attribute changes normally initiate a navigation. We suppress // the next src attribute handler call to avoid reloading the page // on every guest-initiated navigation. - this.setValueIgnoreMutation(oldValue); - return; + this.setValueIgnoreMutation(oldValue) + return } - return this.parse(); + return this.parse() } // The purpose of this mutation observer is to catch assignment to the src // attribute without any changes to its value. This is useful in the case // where the webview guest has crashed and navigating to the same address // spawns off a new process. - setupMutationObserver() { - var params; + setupMutationObserver () { + var params this.observer = new MutationObserver((mutations) => { - var i, len, mutation, newValue, oldValue; + var i, len, mutation, newValue, oldValue for (i = 0, len = mutations.length; i < len; i++) { - mutation = mutations[i]; - oldValue = mutation.oldValue; - newValue = this.getValue(); + mutation = mutations[i] + oldValue = mutation.oldValue + newValue = this.getValue() if (oldValue !== newValue) { - return; + return } - this.handleMutation(oldValue, newValue); + this.handleMutation(oldValue, newValue) } - }); + }) params = { attributes: true, attributeOldValue: true, attributeFilter: [this.name] - }; - return this.observer.observe(this.webViewImpl.webviewNode, params); + } + return this.observer.observe(this.webViewImpl.webviewNode, params) } - parse() { - var guestContents, httpreferrer, opts, useragent; + parse () { + var guestContents, httpreferrer, opts, useragent if (!this.webViewImpl.elementAttached || !this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId || !this.getValue()) { - return; + return } if (this.webViewImpl.guestInstanceId == null) { if (this.webViewImpl.beforeFirstNavigation) { - this.webViewImpl.beforeFirstNavigation = false; - this.webViewImpl.createGuest(); + this.webViewImpl.beforeFirstNavigation = false + this.webViewImpl.createGuest() } - return; + return } // Navigate to |this.src|. - opts = {}; - httpreferrer = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER].getValue(); + opts = {} + httpreferrer = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER].getValue() if (httpreferrer) { - opts.httpReferrer = httpreferrer; + opts.httpReferrer = httpreferrer } - useragent = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_USERAGENT].getValue(); + useragent = this.webViewImpl.attributes[webViewConstants.ATTRIBUTE_USERAGENT].getValue() if (useragent) { - opts.userAgent = useragent; + opts.userAgent = useragent } - guestContents = remote.getGuestWebContents(this.webViewImpl.guestInstanceId); - return guestContents.loadURL(this.getValue(), opts); + guestContents = remote.getGuestWebContents(this.webViewImpl.guestInstanceId) + return guestContents.loadURL(this.getValue(), opts) } } // Attribute specifies HTTP referrer. class HttpReferrerAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_HTTPREFERRER, webViewImpl); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_HTTPREFERRER, webViewImpl) } } // Attribute specifies user agent class UserAgentAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_USERAGENT, webViewImpl); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_USERAGENT, webViewImpl) } } // Attribute that set preload script. class PreloadAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_PRELOAD, webViewImpl); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_PRELOAD, webViewImpl) } - getValue() { - var preload, protocol; + getValue () { + var preload, protocol if (!this.webViewImpl.webviewNode.hasAttribute(this.name)) { - return this.value; + return this.value } - preload = resolveURL(this.webViewImpl.webviewNode.getAttribute(this.name)); - protocol = preload.substr(0, 5); + preload = resolveURL(this.webViewImpl.webviewNode.getAttribute(this.name)) + protocol = preload.substr(0, 5) if (protocol !== 'file:') { - console.error(webViewConstants.ERROR_MSG_INVALID_PRELOAD_ATTRIBUTE); - preload = ''; + console.error(webViewConstants.ERROR_MSG_INVALID_PRELOAD_ATTRIBUTE) + preload = '' } - return preload; + return preload } } // Attribute that specifies the blink features to be enabled. class BlinkFeaturesAttribute extends WebViewAttribute { - constructor(webViewImpl) { - super(webViewConstants.ATTRIBUTE_BLINKFEATURES, webViewImpl); + constructor (webViewImpl) { + super(webViewConstants.ATTRIBUTE_BLINKFEATURES, webViewImpl) } } // Sets up all of the webview attributes. -WebViewImpl.prototype.setupWebViewAttributes = function() { - this.attributes = {}; - this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE] = new AutosizeAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_PARTITION] = new PartitionAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_SRC] = new SrcAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER] = new HttpReferrerAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_USERAGENT] = new UserAgentAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_NODEINTEGRATION] = new BooleanAttribute(webViewConstants.ATTRIBUTE_NODEINTEGRATION, this); - this.attributes[webViewConstants.ATTRIBUTE_PLUGINS] = new BooleanAttribute(webViewConstants.ATTRIBUTE_PLUGINS, this); - this.attributes[webViewConstants.ATTRIBUTE_DISABLEWEBSECURITY] = new BooleanAttribute(webViewConstants.ATTRIBUTE_DISABLEWEBSECURITY, this); - this.attributes[webViewConstants.ATTRIBUTE_ALLOWPOPUPS] = new BooleanAttribute(webViewConstants.ATTRIBUTE_ALLOWPOPUPS, this); - this.attributes[webViewConstants.ATTRIBUTE_PRELOAD] = new PreloadAttribute(this); - this.attributes[webViewConstants.ATTRIBUTE_BLINKFEATURES] = new BlinkFeaturesAttribute(this); +WebViewImpl.prototype.setupWebViewAttributes = function () { + this.attributes = {} + this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE] = new AutosizeAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_PARTITION] = new PartitionAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_SRC] = new SrcAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_HTTPREFERRER] = new HttpReferrerAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_USERAGENT] = new UserAgentAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_NODEINTEGRATION] = new BooleanAttribute(webViewConstants.ATTRIBUTE_NODEINTEGRATION, this) + this.attributes[webViewConstants.ATTRIBUTE_PLUGINS] = new BooleanAttribute(webViewConstants.ATTRIBUTE_PLUGINS, this) + this.attributes[webViewConstants.ATTRIBUTE_DISABLEWEBSECURITY] = new BooleanAttribute(webViewConstants.ATTRIBUTE_DISABLEWEBSECURITY, this) + this.attributes[webViewConstants.ATTRIBUTE_ALLOWPOPUPS] = new BooleanAttribute(webViewConstants.ATTRIBUTE_ALLOWPOPUPS, this) + this.attributes[webViewConstants.ATTRIBUTE_PRELOAD] = new PreloadAttribute(this) + this.attributes[webViewConstants.ATTRIBUTE_BLINKFEATURES] = new BlinkFeaturesAttribute(this) - const autosizeAttributes = [webViewConstants.ATTRIBUTE_MAXHEIGHT, webViewConstants.ATTRIBUTE_MAXWIDTH, webViewConstants.ATTRIBUTE_MINHEIGHT, webViewConstants.ATTRIBUTE_MINWIDTH]; + const autosizeAttributes = [webViewConstants.ATTRIBUTE_MAXHEIGHT, webViewConstants.ATTRIBUTE_MAXWIDTH, webViewConstants.ATTRIBUTE_MINHEIGHT, webViewConstants.ATTRIBUTE_MINWIDTH] autosizeAttributes.forEach((attribute) => { - this.attributes[attribute] = new AutosizeDimensionAttribute(attribute, this); - }); -}; + this.attributes[attribute] = new AutosizeDimensionAttribute(attribute, this) + }) +} diff --git a/lib/renderer/web-view/web-view-constants.js b/lib/renderer/web-view/web-view-constants.js index 297941aa8012..5501f4f3599b 100644 --- a/lib/renderer/web-view/web-view-constants.js +++ b/lib/renderer/web-view/web-view-constants.js @@ -25,4 +25,4 @@ module.exports = { ERROR_MSG_CANNOT_INJECT_SCRIPT: ': ' + 'Script cannot be injected into content until the page has loaded.', ERROR_MSG_INVALID_PARTITION_ATTRIBUTE: 'Invalid partition attribute.', ERROR_MSG_INVALID_PRELOAD_ATTRIBUTE: 'Only "file:" protocol is supported in "preload" attribute.' -}; +} diff --git a/lib/renderer/web-view/web-view.js b/lib/renderer/web-view/web-view.js index 0d85b7549ff8..f03427e5b5fe 100644 --- a/lib/renderer/web-view/web-view.js +++ b/lib/renderer/web-view/web-view.js @@ -1,63 +1,63 @@ -'use strict'; +'use strict' -const deprecate = require('electron').deprecate; -const webFrame = require('electron').webFrame; -const remote = require('electron').remote; -const ipcRenderer = require('electron').ipcRenderer; +const deprecate = require('electron').deprecate +const webFrame = require('electron').webFrame +const remote = require('electron').remote +const ipcRenderer = require('electron').ipcRenderer -const v8Util = process.atomBinding('v8_util'); -const guestViewInternal = require('./guest-view-internal'); -const webViewConstants = require('./web-view-constants'); +const v8Util = process.atomBinding('v8_util') +const guestViewInternal = require('./guest-view-internal') +const webViewConstants = require('./web-view-constants') -var hasProp = {}.hasOwnProperty; +var hasProp = {}.hasOwnProperty // ID generator. -var nextId = 0; +var nextId = 0 -var getNextId = function() { - return ++nextId; -}; +var getNextId = function () { + return ++nextId +} // Represents the internal state of the WebView node. -var WebViewImpl = (function() { - function WebViewImpl(webviewNode) { - var shadowRoot; - this.webviewNode = webviewNode; - v8Util.setHiddenValue(this.webviewNode, 'internal', this); - this.attached = false; - this.elementAttached = false; - this.beforeFirstNavigation = true; +var WebViewImpl = (function () { + function WebViewImpl (webviewNode) { + var shadowRoot + this.webviewNode = webviewNode + v8Util.setHiddenValue(this.webviewNode, 'internal', this) + this.attached = false + this.elementAttached = false + this.beforeFirstNavigation = true // on* Event handlers. - this.on = {}; - this.browserPluginNode = this.createBrowserPluginNode(); - shadowRoot = this.webviewNode.createShadowRoot(); - shadowRoot.innerHTML = ''; - this.setupWebViewAttributes(); - this.setupFocusPropagation(); - this.viewInstanceId = getNextId(); - shadowRoot.appendChild(this.browserPluginNode); + this.on = {} + this.browserPluginNode = this.createBrowserPluginNode() + shadowRoot = this.webviewNode.createShadowRoot() + shadowRoot.innerHTML = '' + this.setupWebViewAttributes() + this.setupFocusPropagation() + this.viewInstanceId = getNextId() + shadowRoot.appendChild(this.browserPluginNode) // Subscribe to host's zoom level changes. this.onZoomLevelChanged = (zoomLevel) => { - this.webviewNode.setZoomLevel(zoomLevel); - }; - webFrame.on('zoom-level-changed', this.onZoomLevelChanged); + this.webviewNode.setZoomLevel(zoomLevel) + } + webFrame.on('zoom-level-changed', this.onZoomLevelChanged) } - WebViewImpl.prototype.createBrowserPluginNode = function() { + WebViewImpl.prototype.createBrowserPluginNode = function () { // We create BrowserPlugin as a custom element in order to observe changes // to attributes synchronously. - var browserPluginNode; - browserPluginNode = new WebViewImpl.BrowserPlugin(); - v8Util.setHiddenValue(browserPluginNode, 'internal', this); - return browserPluginNode; - }; + var browserPluginNode + browserPluginNode = new WebViewImpl.BrowserPlugin() + v8Util.setHiddenValue(browserPluginNode, 'internal', this) + return browserPluginNode + } // Resets some state upon reattaching element to the DOM. - WebViewImpl.prototype.reset = function() { + WebViewImpl.prototype.reset = function () { // Unlisten the zoom-level-changed event. - webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged); + webFrame.removeListener('zoom-level-changed', this.onZoomLevelChanged) // If guestInstanceId is defined then the has navigated and has // already picked up a partition ID. Thus, we need to reset the initialization @@ -66,174 +66,172 @@ var WebViewImpl = (function() { // heard back from createGuest yet. We will not reset the flag in this case so // that we don't end up allocating a second guest. if (this.guestInstanceId) { - guestViewInternal.destroyGuest(this.guestInstanceId); - this.webContents = null; - this.guestInstanceId = void 0; - this.beforeFirstNavigation = true; - this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true; + guestViewInternal.destroyGuest(this.guestInstanceId) + this.webContents = null + this.guestInstanceId = void 0 + this.beforeFirstNavigation = true + this.attributes[webViewConstants.ATTRIBUTE_PARTITION].validPartitionId = true } - return this.internalInstanceId = 0; - }; + return this.internalInstanceId = 0 + } // Sets the .request property. - WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function(request) { + WebViewImpl.prototype.setRequestPropertyOnWebViewNode = function (request) { return Object.defineProperty(this.webviewNode, 'request', { value: request, enumerable: true - }); - }; + }) + } - WebViewImpl.prototype.setupFocusPropagation = function() { + WebViewImpl.prototype.setupFocusPropagation = function () { if (!this.webviewNode.hasAttribute('tabIndex')) { // needs a tabIndex in order to be focusable. // TODO(fsamuel): It would be nice to avoid exposing a tabIndex attribute // to allow to be focusable. // See http://crbug.com/231664. - this.webviewNode.setAttribute('tabIndex', -1); + this.webviewNode.setAttribute('tabIndex', -1) } // Focus the BrowserPlugin when the takes focus. this.webviewNode.addEventListener('focus', () => { - this.browserPluginNode.focus(); - }); + this.browserPluginNode.focus() + }) // Blur the BrowserPlugin when the loses focus. this.webviewNode.addEventListener('blur', () => { - this.browserPluginNode.blur(); - }); - }; - + this.browserPluginNode.blur() + }) + } // This observer monitors mutations to attributes of the and // updates the BrowserPlugin properties accordingly. In turn, updating // a BrowserPlugin property will update the corresponding BrowserPlugin // attribute, if necessary. See BrowserPlugin::UpdateDOMAttribute for more // details. - WebViewImpl.prototype.handleWebviewAttributeMutation = function(attributeName, oldValue, newValue) { + WebViewImpl.prototype.handleWebviewAttributeMutation = function (attributeName, oldValue, newValue) { if (!this.attributes[attributeName] || this.attributes[attributeName].ignoreMutation) { - return; + return } - // Let the changed attribute handle its own mutation; - return this.attributes[attributeName].handleMutation(oldValue, newValue); - }; + // Let the changed attribute handle its own mutation + return this.attributes[attributeName].handleMutation(oldValue, newValue) + } - WebViewImpl.prototype.handleBrowserPluginAttributeMutation = function(attributeName, oldValue, newValue) { + WebViewImpl.prototype.handleBrowserPluginAttributeMutation = function (attributeName, oldValue, newValue) { if (attributeName === webViewConstants.ATTRIBUTE_INTERNALINSTANCEID && !oldValue && !!newValue) { - this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID); - this.internalInstanceId = parseInt(newValue); + this.browserPluginNode.removeAttribute(webViewConstants.ATTRIBUTE_INTERNALINSTANCEID) + this.internalInstanceId = parseInt(newValue) // Track when the element resizes using the element resize callback. - webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this)); + webFrame.registerElementResizeCallback(this.internalInstanceId, this.onElementResize.bind(this)) if (!this.guestInstanceId) { - return; + return } - return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()); + return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()) } - }; + } - WebViewImpl.prototype.onSizeChanged = function(webViewEvent) { - var maxHeight, maxWidth, minHeight, minWidth, newHeight, newWidth, node, width; - newWidth = webViewEvent.newWidth; - newHeight = webViewEvent.newHeight; - node = this.webviewNode; - width = node.offsetWidth; + WebViewImpl.prototype.onSizeChanged = function (webViewEvent) { + var maxHeight, maxWidth, minHeight, minWidth, newHeight, newWidth, node, width + newWidth = webViewEvent.newWidth + newHeight = webViewEvent.newHeight + node = this.webviewNode + width = node.offsetWidth // Check the current bounds to make sure we do not resize // outside of current constraints. - maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width; - maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width; - minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width; - minHeight = this.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() | width; - minWidth = Math.min(minWidth, maxWidth); - minHeight = Math.min(minHeight, maxHeight); + maxWidth = this.attributes[webViewConstants.ATTRIBUTE_MAXWIDTH].getValue() | width + maxHeight = this.attributes[webViewConstants.ATTRIBUTE_MAXHEIGHT].getValue() | width + minWidth = this.attributes[webViewConstants.ATTRIBUTE_MINWIDTH].getValue() | width + minHeight = this.attributes[webViewConstants.ATTRIBUTE_MINHEIGHT].getValue() | width + minWidth = Math.min(minWidth, maxWidth) + minHeight = Math.min(minHeight, maxHeight) if (!this.attributes[webViewConstants.ATTRIBUTE_AUTOSIZE].getValue() || (newWidth >= minWidth && newWidth <= maxWidth && newHeight >= minHeight && newHeight <= maxHeight)) { - node.style.width = newWidth + 'px'; - node.style.height = newHeight + 'px'; + node.style.width = newWidth + 'px' + node.style.height = newHeight + 'px' // Only fire the DOM event if the size of the has actually // changed. - return this.dispatchEvent(webViewEvent); + return this.dispatchEvent(webViewEvent) } - }; + } - WebViewImpl.prototype.onElementResize = function(newSize) { + WebViewImpl.prototype.onElementResize = function (newSize) { // Dispatch the 'resize' event. - var resizeEvent; + var resizeEvent resizeEvent = new Event('resize', { bubbles: true - }); - resizeEvent.newWidth = newSize.width; - resizeEvent.newHeight = newSize.height; - this.dispatchEvent(resizeEvent); + }) + resizeEvent.newWidth = newSize.width + resizeEvent.newHeight = newSize.height + this.dispatchEvent(resizeEvent) if (this.guestInstanceId) { return guestViewInternal.setSize(this.guestInstanceId, { normal: newSize - }); + }) } - }; + } - WebViewImpl.prototype.createGuest = function() { + WebViewImpl.prototype.createGuest = function () { return guestViewInternal.createGuest(this.buildParams(), (event, guestInstanceId) => { - this.attachWindow(guestInstanceId); - }); - }; + this.attachWindow(guestInstanceId) + }) + } - WebViewImpl.prototype.dispatchEvent = function(webViewEvent) { - return this.webviewNode.dispatchEvent(webViewEvent); - }; + WebViewImpl.prototype.dispatchEvent = function (webViewEvent) { + return this.webviewNode.dispatchEvent(webViewEvent) + } // Adds an 'on' property on the webview, which can be used to set/unset // an event handler. - WebViewImpl.prototype.setupEventProperty = function(eventName) { - var propertyName; - propertyName = 'on' + eventName.toLowerCase(); + WebViewImpl.prototype.setupEventProperty = function (eventName) { + var propertyName + propertyName = 'on' + eventName.toLowerCase() return Object.defineProperty(this.webviewNode, propertyName, { get: () => { - return this.on[propertyName]; + return this.on[propertyName] }, set: (value) => { if (this.on[propertyName]) { - this.webviewNode.removeEventListener(eventName, this.on[propertyName]); + this.webviewNode.removeEventListener(eventName, this.on[propertyName]) } - this.on[propertyName] = value; + this.on[propertyName] = value if (value) { - return this.webviewNode.addEventListener(eventName, value); + return this.webviewNode.addEventListener(eventName, value) } }, enumerable: true - }); - }; + }) + } // Updates state upon loadcommit. - WebViewImpl.prototype.onLoadCommit = function(webViewEvent) { - var newValue, oldValue; - oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC); - newValue = webViewEvent.url; + WebViewImpl.prototype.onLoadCommit = function (webViewEvent) { + var newValue, oldValue + oldValue = this.webviewNode.getAttribute(webViewConstants.ATTRIBUTE_SRC) + newValue = webViewEvent.url if (webViewEvent.isMainFrame && (oldValue !== newValue)) { - // Touching the src attribute triggers a navigation. To avoid // triggering a page reload on every guest-initiated navigation, // we do not handle this mutation. - return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue); + return this.attributes[webViewConstants.ATTRIBUTE_SRC].setValueIgnoreMutation(newValue) } - }; + } - WebViewImpl.prototype.onAttach = function(storagePartitionId) { - return this.attributes[webViewConstants.ATTRIBUTE_PARTITION].setValue(storagePartitionId); - }; + WebViewImpl.prototype.onAttach = function (storagePartitionId) { + return this.attributes[webViewConstants.ATTRIBUTE_PARTITION].setValue(storagePartitionId) + } - WebViewImpl.prototype.buildParams = function() { - var attribute, attributeName, css, elementRect, params, ref1; + WebViewImpl.prototype.buildParams = function () { + var attribute, attributeName, css, elementRect, params, ref1 params = { instanceId: this.viewInstanceId, userAgentOverride: this.userAgentOverride - }; - ref1 = this.attributes; + } + ref1 = this.attributes for (attributeName in ref1) { - if (!hasProp.call(ref1, attributeName)) continue; - attribute = ref1[attributeName]; - params[attributeName] = attribute.getValue(); + if (!hasProp.call(ref1, attributeName)) continue + attribute = ref1[attributeName] + params[attributeName] = attribute.getValue() } // When the WebView is not participating in layout (display:none) @@ -241,96 +239,95 @@ var WebViewImpl = (function() { // However, in the case where the WebView has a fixed size we can // use that value to initially size the guest so as to avoid a relayout of // the on display:block. - css = window.getComputedStyle(this.webviewNode, null); - elementRect = this.webviewNode.getBoundingClientRect(); - params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width')); - params.elementHeight = parseInt(elementRect.height) || parseInt(css.getPropertyValue('height')); - return params; - }; + css = window.getComputedStyle(this.webviewNode, null) + elementRect = this.webviewNode.getBoundingClientRect() + params.elementWidth = parseInt(elementRect.width) || parseInt(css.getPropertyValue('width')) + params.elementHeight = parseInt(elementRect.height) || parseInt(css.getPropertyValue('height')) + return params + } - WebViewImpl.prototype.attachWindow = function(guestInstanceId) { - this.guestInstanceId = guestInstanceId; - this.webContents = remote.getGuestWebContents(this.guestInstanceId); + WebViewImpl.prototype.attachWindow = function (guestInstanceId) { + this.guestInstanceId = guestInstanceId + this.webContents = remote.getGuestWebContents(this.guestInstanceId) if (!this.internalInstanceId) { - return true; + return true } - return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()); - }; + return guestViewInternal.attachGuest(this.internalInstanceId, this.guestInstanceId, this.buildParams()) + } - return WebViewImpl; - -})(); + return WebViewImpl +})() // Registers browser plugin custom element. -var registerBrowserPluginElement = function() { - var proto; - proto = Object.create(HTMLObjectElement.prototype); - proto.createdCallback = function() { - this.setAttribute('type', 'application/browser-plugin'); - this.setAttribute('id', 'browser-plugin-' + getNextId()); +var registerBrowserPluginElement = function () { + var proto + proto = Object.create(HTMLObjectElement.prototype) + proto.createdCallback = function () { + this.setAttribute('type', 'application/browser-plugin') + this.setAttribute('id', 'browser-plugin-' + getNextId()) // The node fills in the container. - return this.style.flex = '1 1 auto'; - }; - proto.attributeChangedCallback = function(name, oldValue, newValue) { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + return this.style.flex = '1 1 auto' + } + proto.attributeChangedCallback = function (name, oldValue, newValue) { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue); - }; - proto.attachedCallback = function() { + return internal.handleBrowserPluginAttributeMutation(name, oldValue, newValue) + } + proto.attachedCallback = function () { // Load the plugin immediately. - return this.nonExistentAttribute; - }; + return this.nonExistentAttribute + } WebViewImpl.BrowserPlugin = webFrame.registerEmbedderCustomElement('browserplugin', { - "extends": 'object', + 'extends': 'object', prototype: proto - }); - delete proto.createdCallback; - delete proto.attachedCallback; - delete proto.detachedCallback; - return delete proto.attributeChangedCallback; -}; + }) + delete proto.createdCallback + delete proto.attachedCallback + delete proto.detachedCallback + return delete proto.attributeChangedCallback +} // Registers custom element. -var registerWebViewElement = function() { - var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto; - proto = Object.create(HTMLObjectElement.prototype); - proto.createdCallback = function() { - return new WebViewImpl(this); - }; - proto.attributeChangedCallback = function(name, oldValue, newValue) { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); +var registerWebViewElement = function () { + var createBlockHandler, createNonBlockHandler, i, j, len, len1, m, methods, nonblockMethods, proto + proto = Object.create(HTMLObjectElement.prototype) + proto.createdCallback = function () { + return new WebViewImpl(this) + } + proto.attributeChangedCallback = function (name, oldValue, newValue) { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - return internal.handleWebviewAttributeMutation(name, oldValue, newValue); - }; - proto.detachedCallback = function() { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + return internal.handleWebviewAttributeMutation(name, oldValue, newValue) + } + proto.detachedCallback = function () { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } - guestViewInternal.deregisterEvents(internal.viewInstanceId); - internal.elementAttached = false; - return internal.reset(); - }; - proto.attachedCallback = function() { - var internal; - internal = v8Util.getHiddenValue(this, 'internal'); + guestViewInternal.deregisterEvents(internal.viewInstanceId) + internal.elementAttached = false + return internal.reset() + } + proto.attachedCallback = function () { + var internal + internal = v8Util.getHiddenValue(this, 'internal') if (!internal) { - return; + return } if (!internal.elementAttached) { - guestViewInternal.registerEvents(internal, internal.viewInstanceId); - internal.elementAttached = true; - return internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse(); + guestViewInternal.registerEvents(internal, internal.viewInstanceId) + internal.elementAttached = true + return internal.attributes[webViewConstants.ATTRIBUTE_SRC].parse() } - }; + } // Public-facing API methods. methods = [ @@ -378,7 +375,7 @@ var registerWebViewElement = function() { 'inspectServiceWorker', 'print', 'printToPDF', - ]; + ] nonblockMethods = [ 'insertCSS', 'insertText', @@ -387,79 +384,79 @@ var registerWebViewElement = function() { 'setZoomFactor', 'setZoomLevel', 'setZoomLevelLimits', - ]; + ] // Forward proto.foo* method calls to WebViewImpl.foo*. - createBlockHandler = function(m) { - return function(...args) { - const internal = v8Util.getHiddenValue(this, 'internal'); + createBlockHandler = function (m) { + return function (...args) { + const internal = v8Util.getHiddenValue(this, 'internal') if (internal.webContents) { - return internal.webContents[m].apply(internal.webContents, args); + return internal.webContents[m].apply(internal.webContents, args) } else { - throw new Error(`Cannot call ${m} because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.`); + throw new Error(`Cannot call ${m} because the webContents is unavailable. The WebView must be attached to the DOM and the dom-ready event emitted before this method can be called.`) } - }; - }; - for (i = 0, len = methods.length; i < len; i++) { - m = methods[i]; - proto[m] = createBlockHandler(m); + } + } + for (i = 0, len = methods.length; i < len; i++) { + m = methods[i] + proto[m] = createBlockHandler(m) + } + createNonBlockHandler = function (m) { + return function (...args) { + const internal = v8Util.getHiddenValue(this, 'internal') + return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)) + } } - createNonBlockHandler = function(m) { - return function(...args) { - const internal = v8Util.getHiddenValue(this, 'internal'); - return ipcRenderer.send.apply(ipcRenderer, ['ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', null, internal.guestInstanceId, m].concat(args)); - }; - }; for (j = 0, len1 = nonblockMethods.length; j < len1; j++) { - m = nonblockMethods[j]; - proto[m] = createNonBlockHandler(m); + m = nonblockMethods[j] + proto[m] = createNonBlockHandler(m) } - proto.executeJavaScript = function(code, hasUserGesture, callback) { - var internal = v8Util.getHiddenValue(this, 'internal'); - if (typeof hasUserGesture === "function") { - callback = hasUserGesture; - hasUserGesture = false; + proto.executeJavaScript = function (code, hasUserGesture, callback) { + var internal = v8Util.getHiddenValue(this, 'internal') + if (typeof hasUserGesture === 'function') { + callback = hasUserGesture + hasUserGesture = false } - let requestId = getNextId(); - ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, "executeJavaScript", code, hasUserGesture); - ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function(event, result) { + let requestId = getNextId() + ipcRenderer.send('ATOM_BROWSER_ASYNC_CALL_TO_GUEST_VIEW', requestId, internal.guestInstanceId, 'executeJavaScript', code, hasUserGesture) + ipcRenderer.once(`ATOM_RENDERER_ASYNC_CALL_TO_GUEST_VIEW_RESPONSE_${requestId}`, function (event, result) { if (callback) - callback(result); - }); - }; + callback(result) + }) + } // WebContents associated with this webview. - proto.getWebContents = function() { - var internal = v8Util.getHiddenValue(this, 'internal'); - return internal.webContents; - }; + proto.getWebContents = function () { + var internal = v8Util.getHiddenValue(this, 'internal') + return internal.webContents + } // Deprecated. - deprecate.rename(proto, 'getUrl', 'getURL'); + deprecate.rename(proto, 'getUrl', 'getURL') window.WebView = webFrame.registerEmbedderCustomElement('webview', { prototype: proto - }); + }) // Delete the callbacks so developers cannot call them and produce unexpected // behavior. - delete proto.createdCallback; - delete proto.attachedCallback; - delete proto.detachedCallback; - return delete proto.attributeChangedCallback; -}; + delete proto.createdCallback + delete proto.attachedCallback + delete proto.detachedCallback + return delete proto.attributeChangedCallback +} -var useCapture = true; +var useCapture = true -var listener = function(event) { +var listener = function (event) { if (document.readyState === 'loading') { - return; + return } - registerBrowserPluginElement(); - registerWebViewElement(); - return window.removeEventListener(event.type, listener, useCapture); -}; + registerBrowserPluginElement() + registerWebViewElement() + return window.removeEventListener(event.type, listener, useCapture) +} -window.addEventListener('readystatechange', listener, true); +window.addEventListener('readystatechange', listener, true) -module.exports = WebViewImpl; +module.exports = WebViewImpl diff --git a/spec/api-app-spec.js b/spec/api-app-spec.js index 1b12f6f733ce..2a5417b9c50e 100644 --- a/spec/api-app-spec.js +++ b/spec/api-app-spec.js @@ -1,135 +1,135 @@ -const assert = require('assert'); -const ChildProcess = require('child_process'); -const path = require('path'); -const remote = require('electron').remote; +const assert = require('assert') +const ChildProcess = require('child_process') +const path = require('path') +const remote = require('electron').remote -const app = remote.require('electron').app; -const BrowserWindow = remote.require('electron').BrowserWindow; +const app = remote.require('electron').app +const BrowserWindow = remote.require('electron').BrowserWindow -describe('electron module', function() { - it('allows old style require by default', function() { - require('shell'); - }); +describe('electron module', function () { + it('allows old style require by default', function () { + require('shell') + }) - it('can prevent exposing internal modules to require', function(done) { - const electron = require('electron'); - const clipboard = require('clipboard'); - assert.equal(typeof clipboard, 'object'); - electron.hideInternalModules(); + it('can prevent exposing internal modules to require', function (done) { + const electron = require('electron') + const clipboard = require('clipboard') + assert.equal(typeof clipboard, 'object') + electron.hideInternalModules() try { - require('clipboard'); + require('clipboard') } catch(err) { - assert.equal(err.message, 'Cannot find module \'clipboard\''); - done(); + assert.equal(err.message, "Cannot find module 'clipboard'") + done() } - }); -}); + }) +}) -describe('app module', function() { - describe('app.getVersion()', function() { - it('returns the version field of package.json', function() { - assert.equal(app.getVersion(), '0.1.0'); - }); - }); +describe('app module', function () { + describe('app.getVersion()', function () { + it('returns the version field of package.json', function () { + assert.equal(app.getVersion(), '0.1.0') + }) + }) - describe('app.setVersion(version)', function() { - it('overrides the version', function() { - assert.equal(app.getVersion(), '0.1.0'); - app.setVersion('test-version'); - assert.equal(app.getVersion(), 'test-version'); - app.setVersion('0.1.0'); - }); - }); + describe('app.setVersion(version)', function () { + it('overrides the version', function () { + assert.equal(app.getVersion(), '0.1.0') + app.setVersion('test-version') + assert.equal(app.getVersion(), 'test-version') + app.setVersion('0.1.0') + }) + }) - describe('app.getName()', function() { - it('returns the name field of package.json', function() { - assert.equal(app.getName(), 'Electron Test'); - }); - }); + describe('app.getName()', function () { + it('returns the name field of package.json', function () { + assert.equal(app.getName(), 'Electron Test') + }) + }) - describe('app.setName(name)', function() { - it('overrides the name', function() { - assert.equal(app.getName(), 'Electron Test'); - app.setName('test-name'); - assert.equal(app.getName(), 'test-name'); - app.setName('Electron Test'); - }); - }); + describe('app.setName(name)', function () { + it('overrides the name', function () { + assert.equal(app.getName(), 'Electron Test') + app.setName('test-name') + assert.equal(app.getName(), 'test-name') + app.setName('Electron Test') + }) + }) - describe('app.getLocale()', function() { - it('should not be empty', function() { - assert.notEqual(app.getLocale(), ''); - }); - }); + describe('app.getLocale()', function () { + it('should not be empty', function () { + assert.notEqual(app.getLocale(), '') + }) + }) - describe('app.exit(exitCode)', function() { - var appProcess = null; + describe('app.exit(exitCode)', function () { + var appProcess = null - afterEach(function() { - appProcess != null ? appProcess.kill() : void 0; - }); + afterEach(function () { + appProcess != null ? appProcess.kill() : void 0 + }) - it('emits a process exit event with the code', function(done) { - var appPath = path.join(__dirname, 'fixtures', 'api', 'quit-app'); - var electronPath = remote.getGlobal('process').execPath; - var output = ''; - appProcess = ChildProcess.spawn(electronPath, [appPath]); - appProcess.stdout.on('data', function(data) { - output += data; - }); - appProcess.on('close', function(code) { + it('emits a process exit event with the code', function (done) { + var appPath = path.join(__dirname, 'fixtures', 'api', 'quit-app') + var electronPath = remote.getGlobal('process').execPath + var output = '' + appProcess = ChildProcess.spawn(electronPath, [appPath]) + appProcess.stdout.on('data', function (data) { + output += data + }) + appProcess.on('close', function (code) { if (process.platform !== 'win32') { - assert.notEqual(output.indexOf('Exit event with code: 123'), -1); + assert.notEqual(output.indexOf('Exit event with code: 123'), -1) } - assert.equal(code, 123); - done(); - }); - }); - }); + assert.equal(code, 123) + done() + }) + }) + }) - describe('BrowserWindow events', function() { - var w = null; + describe('BrowserWindow events', function () { + var w = null - afterEach(function() { + afterEach(function () { if (w != null) { - w.destroy(); + w.destroy() } - w = null; - }); + w = null + }) - it('should emit browser-window-focus event when window is focused', function(done) { - app.once('browser-window-focus', function(e, window) { - assert.equal(w.id, window.id); - done(); - }); + it('should emit browser-window-focus event when window is focused', function (done) { + app.once('browser-window-focus', function (e, window) { + assert.equal(w.id, window.id) + done() + }) w = new BrowserWindow({ show: false - }); - w.emit('focus'); - }); + }) + w.emit('focus') + }) - it('should emit browser-window-blur event when window is blured', function(done) { - app.once('browser-window-blur', function(e, window) { - assert.equal(w.id, window.id); - done(); - }); + it('should emit browser-window-blur event when window is blured', function (done) { + app.once('browser-window-blur', function (e, window) { + assert.equal(w.id, window.id) + done() + }) w = new BrowserWindow({ show: false - }); - w.emit('blur'); - }); + }) + w.emit('blur') + }) - it('should emit browser-window-created event when window is created', function(done) { - app.once('browser-window-created', function(e, window) { - setImmediate(function() { - assert.equal(w.id, window.id); - done(); - }); - }); + it('should emit browser-window-created event when window is created', function (done) { + app.once('browser-window-created', function (e, window) { + setImmediate(function () { + assert.equal(w.id, window.id) + done() + }) + }) w = new BrowserWindow({ show: false - }); - w.emit('blur'); - }); - }); -}); + }) + w.emit('blur') + }) + }) +})