merge changes from master

This commit is contained in:
liusi 2016-11-01 10:20:47 +08:00
commit 7880d37d73
126 changed files with 5549 additions and 896 deletions

View file

@ -5,7 +5,7 @@
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron?type=dev)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
:memo: Available Translations: [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/project/README.md) | [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN/project/README.md) | [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR/project/README.md)
:memo: Available Translations: [Korean](https://github.com/electron/electron/tree/master/docs-translations/ko-KR/project/README.md) | [Simplified Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-CN/project/README.md) | [Brazilian Portuguese](https://github.com/electron/electron/tree/master/docs-translations/pt-BR/project/README.md) | [Traditional Chinese](https://github.com/electron/electron/tree/master/docs-translations/zh-TW/project/README.md)
The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [Node.js](https://nodejs.org/) and

View file

@ -0,0 +1,61 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_net.h"
#include "atom/browser/api/atom_api_url_request.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace atom {
namespace api {
Net::Net(v8::Isolate* isolate) {
Init(isolate);
}
Net::~Net() {}
// static
v8::Local<v8::Value> Net::Create(v8::Isolate* isolate) {
return mate::CreateHandle(isolate, new Net(isolate)).ToV8();
}
// static
void Net::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "Net"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
.SetProperty("URLRequest", &Net::URLRequest);
}
v8::Local<v8::Value> Net::URLRequest(v8::Isolate* isolate) {
return URLRequest::GetConstructor(isolate)->GetFunction();
}
} // namespace api
} // namespace atom
namespace {
using atom::api::Net;
using atom::api::URLRequest;
void Initialize(v8::Local<v8::Object> exports,
v8::Local<v8::Value> unused,
v8::Local<v8::Context> context,
void* priv) {
v8::Isolate* isolate = context->GetIsolate();
URLRequest::SetConstructor(isolate, base::Bind(URLRequest::New));
mate::Dictionary dict(isolate, exports);
dict.Set("net", Net::Create(isolate));
dict.Set("Net", Net::GetConstructor(isolate)->GetFunction());
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_net, Initialize)

View file

@ -0,0 +1,35 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_NET_H_
#define ATOM_BROWSER_API_ATOM_API_NET_H_
#include "atom/browser/api/event_emitter.h"
namespace atom {
namespace api {
class Net : public mate::EventEmitter<Net> {
public:
static v8::Local<v8::Value> Create(v8::Isolate* isolate);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
v8::Local<v8::Value> URLRequest(v8::Isolate* isolate);
protected:
explicit Net(v8::Isolate* isolate);
~Net() override;
private:
DISALLOW_COPY_AND_ASSIGN(Net);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_NET_H_

View file

@ -0,0 +1,435 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_url_request.h"
#include <string>
#include "atom/browser/api/atom_api_session.h"
#include "atom/browser/net/atom_url_request.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace mate {
template <>
struct Converter<scoped_refptr<const net::IOBufferWithSize>> {
static v8::Local<v8::Value> ToV8(
v8::Isolate* isolate,
scoped_refptr<const net::IOBufferWithSize> buffer) {
return node::Buffer::Copy(isolate, buffer->data(), buffer->size())
.ToLocalChecked();
}
static bool FromV8(v8::Isolate* isolate,
v8::Local<v8::Value> val,
scoped_refptr<const net::IOBufferWithSize>* out) {
auto size = node::Buffer::Length(val);
if (size == 0) {
// Support conversion from empty buffer. A use case is
// a GET request without body.
// Since zero-sized IOBuffer(s) are not supported, we set the
// out pointer to null.
*out = nullptr;
return true;
}
auto data = node::Buffer::Data(val);
if (!data) {
// This is an error as size is positive but data is null.
return false;
}
*out = new net::IOBufferWithSize(size);
// We do a deep copy. We could have used Buffer's internal memory
// but that is much more complicated to be properly handled.
memcpy((*out)->data(), data, size);
return true;
}
};
} // namespace mate
namespace atom {
namespace api {
template <typename Flags>
URLRequest::StateBase<Flags>::StateBase(Flags initialState)
: state_(initialState) {}
template <typename Flags>
void URLRequest::StateBase<Flags>::SetFlag(Flags flag) {
state_ =
static_cast<Flags>(static_cast<int>(state_) | static_cast<int>(flag));
}
template <typename Flags>
bool URLRequest::StateBase<Flags>::operator==(Flags flag) const {
return state_ == flag;
}
template <typename Flags>
bool URLRequest::StateBase<Flags>::IsFlagSet(Flags flag) const {
return static_cast<int>(state_) & static_cast<int>(flag);
}
URLRequest::RequestState::RequestState()
: StateBase(RequestStateFlags::kNotStarted) {}
bool URLRequest::RequestState::NotStarted() const {
return *this == RequestStateFlags::kNotStarted;
}
bool URLRequest::RequestState::Started() const {
return IsFlagSet(RequestStateFlags::kStarted);
}
bool URLRequest::RequestState::Finished() const {
return IsFlagSet(RequestStateFlags::kFinished);
}
bool URLRequest::RequestState::Canceled() const {
return IsFlagSet(RequestStateFlags::kCanceled);
}
bool URLRequest::RequestState::Failed() const {
return IsFlagSet(RequestStateFlags::kFailed);
}
bool URLRequest::RequestState::Closed() const {
return IsFlagSet(RequestStateFlags::kClosed);
}
URLRequest::ResponseState::ResponseState()
: StateBase(ResponseStateFlags::kNotStarted) {}
bool URLRequest::ResponseState::NotStarted() const {
return *this == ResponseStateFlags::kNotStarted;
}
bool URLRequest::ResponseState::Started() const {
return IsFlagSet(ResponseStateFlags::kStarted);
}
bool URLRequest::ResponseState::Ended() const {
return IsFlagSet(ResponseStateFlags::kEnded);
}
bool URLRequest::ResponseState::Failed() const {
return IsFlagSet(ResponseStateFlags::kFailed);
}
URLRequest::URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
InitWith(isolate, wrapper);
}
URLRequest::~URLRequest() {
// A request has been created in JS, it was not used and then
// it got collected, no close event to cleanup, only destructor
// is called.
if (atom_request_) {
atom_request_->Terminate();
}
}
// static
mate::WrappableBase* URLRequest::New(mate::Arguments* args) {
auto isolate = args->isolate();
v8::Local<v8::Object> options;
args->GetNext(&options);
mate::Dictionary dict(isolate, options);
std::string method;
dict.Get("method", &method);
std::string url;
dict.Get("url", &url);
std::string partition;
mate::Handle<api::Session> session;
if (dict.Get("session", &session)) {
} else if (dict.Get("partition", &partition)) {
session = Session::FromPartition(isolate, partition);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "");
}
auto browser_context = session->browser_context();
auto api_url_request = new URLRequest(args->isolate(), args->GetThis());
auto atom_url_request =
AtomURLRequest::Create(browser_context, method, url, api_url_request);
api_url_request->atom_request_ = atom_url_request;
return api_url_request;
}
// static
void URLRequest::BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype) {
prototype->SetClassName(mate::StringToV8(isolate, "URLRequest"));
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
// Request API
.MakeDestroyable()
.SetMethod("write", &URLRequest::Write)
.SetMethod("cancel", &URLRequest::Cancel)
.SetMethod("setExtraHeader", &URLRequest::SetExtraHeader)
.SetMethod("removeExtraHeader", &URLRequest::RemoveExtraHeader)
.SetMethod("setChunkedUpload", &URLRequest::SetChunkedUpload)
.SetProperty("notStarted", &URLRequest::NotStarted)
.SetProperty("finished", &URLRequest::Finished)
// Response APi
.SetProperty("statusCode", &URLRequest::StatusCode)
.SetProperty("statusMessage", &URLRequest::StatusMessage)
.SetProperty("rawResponseHeaders", &URLRequest::RawResponseHeaders)
.SetProperty("httpVersionMajor", &URLRequest::ResponseHttpVersionMajor)
.SetProperty("httpVersionMinor", &URLRequest::ResponseHttpVersionMinor);
}
bool URLRequest::NotStarted() const {
return request_state_.NotStarted();
}
bool URLRequest::Finished() const {
return request_state_.Finished();
}
bool URLRequest::Canceled() const {
return request_state_.Canceled();
}
bool URLRequest::Write(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last) {
if (request_state_.Canceled() || request_state_.Failed() ||
request_state_.Finished() || request_state_.Closed()) {
return false;
}
if (request_state_.NotStarted()) {
request_state_.SetFlag(RequestStateFlags::kStarted);
// Pin on first write.
Pin();
}
if (is_last) {
request_state_.SetFlag(RequestStateFlags::kFinished);
EmitRequestEvent(true, "finish");
}
DCHECK(atom_request_);
if (atom_request_) {
return atom_request_->Write(buffer, is_last);
}
return false;
}
void URLRequest::Cancel() {
if (request_state_.Canceled() || request_state_.Closed()) {
// Cancel only once.
return;
}
// Mark as canceled.
request_state_.SetFlag(RequestStateFlags::kCanceled);
DCHECK(atom_request_);
if (atom_request_ && request_state_.Started()) {
// Really cancel if it was started.
atom_request_->Cancel();
}
EmitRequestEvent(true, "abort");
if (response_state_.Started() && !response_state_.Ended()) {
EmitResponseEvent(true, "aborted");
}
Close();
}
bool URLRequest::SetExtraHeader(const std::string& name,
const std::string& value) {
// Request state must be in the initial non started state.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return false;
}
if (!net::HttpUtil::IsValidHeaderName(name)) {
return false;
}
if (!net::HttpUtil::IsValidHeaderValue(value)) {
return false;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->SetExtraHeader(name, value);
}
return true;
}
void URLRequest::RemoveExtraHeader(const std::string& name) {
// State must be equal to not started.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->RemoveExtraHeader(name);
}
}
void URLRequest::SetChunkedUpload(bool is_chunked_upload) {
// State must be equal to not started.
if (!request_state_.NotStarted()) {
// Cannot change headers after send.
return;
}
DCHECK(atom_request_);
if (atom_request_) {
atom_request_->SetChunkedUpload(is_chunked_upload);
}
}
void URLRequest::OnAuthenticationRequired(
scoped_refptr<const net::AuthChallengeInfo> auth_info) {
if (request_state_.Canceled() || request_state_.Closed()) {
return;
}
DCHECK(atom_request_);
if (!atom_request_) {
return;
}
Emit("login", auth_info.get(),
base::Bind(&AtomURLRequest::PassLoginInformation, atom_request_));
}
void URLRequest::OnResponseStarted(
scoped_refptr<net::HttpResponseHeaders> response_headers) {
if (request_state_.Canceled() || request_state_.Failed() ||
request_state_.Closed()) {
// Don't emit any event after request cancel.
return;
}
response_headers_ = response_headers;
response_state_.SetFlag(ResponseStateFlags::kStarted);
Emit("response");
}
void URLRequest::OnResponseData(
scoped_refptr<const net::IOBufferWithSize> buffer) {
if (request_state_.Canceled() || request_state_.Closed() ||
request_state_.Failed() || response_state_.Failed()) {
// In case we received an unexpected event from Chromium net,
// don't emit any data event after request cancel/error/close.
return;
}
if (!buffer || !buffer->data() || !buffer->size()) {
return;
}
Emit("data", buffer);
}
void URLRequest::OnResponseCompleted() {
if (request_state_.Canceled() || request_state_.Closed() ||
request_state_.Failed() || response_state_.Failed()) {
// In case we received an unexpected event from Chromium net,
// don't emit any data event after request cancel/error/close.
return;
}
response_state_.SetFlag(ResponseStateFlags::kEnded);
Emit("end");
Close();
}
void URLRequest::OnError(const std::string& error, bool isRequestError) {
auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));
if (isRequestError) {
request_state_.SetFlag(RequestStateFlags::kFailed);
EmitRequestEvent(false, "error", error_object);
} else {
response_state_.SetFlag(ResponseStateFlags::kFailed);
EmitResponseEvent(false, "error", error_object);
}
Close();
}
int URLRequest::StatusCode() const {
if (response_headers_) {
return response_headers_->response_code();
}
return -1;
}
std::string URLRequest::StatusMessage() const {
std::string result;
if (response_headers_) {
result = response_headers_->GetStatusText();
}
return result;
}
net::HttpResponseHeaders* URLRequest::RawResponseHeaders() const {
return response_headers_.get();
}
uint32_t URLRequest::ResponseHttpVersionMajor() const {
if (response_headers_) {
return response_headers_->GetHttpVersion().major_value();
}
return 0;
}
uint32_t URLRequest::ResponseHttpVersionMinor() const {
if (response_headers_) {
return response_headers_->GetHttpVersion().minor_value();
}
return 0;
}
void URLRequest::Close() {
if (!request_state_.Closed()) {
request_state_.SetFlag(RequestStateFlags::kClosed);
if (response_state_.Started()) {
// Emit a close event if we really have a response object.
EmitResponseEvent(true, "close");
}
EmitRequestEvent(true, "close");
}
Unpin();
if (atom_request_) {
// A request has been created in JS, used and then it ended.
// We release unneeded net resources.
atom_request_->Terminate();
}
atom_request_ = nullptr;
}
void URLRequest::Pin() {
if (wrapper_.IsEmpty()) {
wrapper_.Reset(isolate(), GetWrapper());
}
}
void URLRequest::Unpin() {
wrapper_.Reset();
}
template <typename... Args>
void URLRequest::EmitRequestEvent(Args... args) {
v8::HandleScope handle_scope(isolate());
mate::CustomEmit(isolate(), GetWrapper(), "_emitRequestEvent", args...);
}
template <typename... Args>
void URLRequest::EmitResponseEvent(Args... args) {
v8::HandleScope handle_scope(isolate());
mate::CustomEmit(isolate(), GetWrapper(), "_emitResponseEvent", args...);
}
} // namespace api
} // namespace atom

View file

@ -0,0 +1,206 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
#define ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
#include <array>
#include <string>
#include "atom/browser/api/event_emitter.h"
#include "atom/browser/api/trackable_object.h"
#include "base/memory/weak_ptr.h"
#include "native_mate/dictionary.h"
#include "native_mate/handle.h"
#include "native_mate/wrappable_base.h"
#include "net/base/auth.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request_context.h"
namespace atom {
class AtomURLRequest;
namespace api {
//
// The URLRequest class implements the V8 binding between the JavaScript API
// and Chromium native net library. It is responsible for handling HTTP/HTTPS
// requests.
//
// The current class provides only the binding layer. Two other JavaScript
// classes (ClientRequest and IncomingMessage) in the net module provide the
// final API, including some state management and arguments validation.
//
// URLRequest's methods fall into two main categories: command and event
// methods. They are always executed on the Browser's UI thread.
// Command methods are called directly from JavaScript code via the API defined
// in BuildPrototype. A command method is generally implemented by forwarding
// the call to a corresponding method on AtomURLRequest which does the
// synchronization on the Browser IO thread. The latter then calls into Chromium
// net library. On the other hand, net library events originate on the IO
// thread in AtomURLRequest and are synchronized back on the UI thread, then
// forwarded to a corresponding event method in URLRequest and then to
// JavaScript via the EmitRequestEvent/EmitResponseEvent helpers.
//
// URLRequest lifetime management: we followed the Wrapper/Wrappable pattern
// defined in native_mate. However, we augment that pattern with a pin/unpin
// mechanism. The main reason is that we want the JS API to provide a similar
// lifetime guarantees as the XMLHttpRequest.
// https://xhr.spec.whatwg.org/#garbage-collection
//
// The primary motivation is to not garbage collect a URLInstance as long as the
// object is emitting network events. For instance, in the following JS code
//
// (function() {
// let request = new URLRequest(...);
// request.on('response', (response)=>{
// response.on('data', (data) = > {
// console.log(data.toString());
// });
// });
// })();
//
// we still want data to be logged even if the response/request objects are n
// more referenced in JavaScript.
//
// Binding by simply following the native_mate Wrapper/Wrappable pattern will
// delete the URLRequest object when the corresponding JS object is collected.
// The v8 handle is a private member in WrappableBase and it is always weak,
// there is no way to make it strong without changing native_mate.
// The solution we implement consists of maintaining some kind of state that
// prevents collection of JS wrappers as long as the request is emitting network
// events. At initialization, the object is unpinned. When the request starts,
// it is pinned. When no more events would be emitted, the object is unpinned
// and lifetime is again managed by the standard native mate Wrapper/Wrappable
// pattern.
//
// pin/unpin: are implemented by constructing/reseting a V8 strong persistent
// handle.
//
// The URLRequest/AtmURLRequest interaction could have been implemented in a
// single class. However, it implies that the resulting class lifetime will be
// managed by two conflicting mechanisms: JavaScript garbage collection and
// Chromium reference counting. Reasoning about lifetime issues become much
// more complex.
//
// We chose to split the implementation into two classes linked via a
// reference counted/raw pointers. A URLRequest instance is deleted if it is
// unpinned and the corresponding JS wrapper object is garbage collected. On the
// other hand, an AtmURLRequest instance lifetime is totally governed by
// reference counting.
//
class URLRequest : public mate::EventEmitter<URLRequest> {
public:
static mate::WrappableBase* New(mate::Arguments* args);
static void BuildPrototype(v8::Isolate* isolate,
v8::Local<v8::FunctionTemplate> prototype);
// Methods for reporting events into JavaScript.
void OnAuthenticationRequired(
scoped_refptr<const net::AuthChallengeInfo> auth_info);
void OnResponseStarted(
scoped_refptr<net::HttpResponseHeaders> response_headers);
void OnResponseData(scoped_refptr<const net::IOBufferWithSize> data);
void OnResponseCompleted();
void OnError(const std::string& error, bool isRequestError);
protected:
explicit URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
~URLRequest() override;
private:
template <typename Flags>
class StateBase {
public:
void SetFlag(Flags flag);
protected:
explicit StateBase(Flags initialState);
bool operator==(Flags flag) const;
bool IsFlagSet(Flags flag) const;
private:
Flags state_;
};
enum class RequestStateFlags {
kNotStarted = 0x0,
kStarted = 0x1,
kFinished = 0x2,
kCanceled = 0x4,
kFailed = 0x8,
kClosed = 0x10
};
class RequestState : public StateBase<RequestStateFlags> {
public:
RequestState();
bool NotStarted() const;
bool Started() const;
bool Finished() const;
bool Canceled() const;
bool Failed() const;
bool Closed() const;
};
enum class ResponseStateFlags {
kNotStarted = 0x0,
kStarted = 0x1,
kEnded = 0x2,
kFailed = 0x4
};
class ResponseState : public StateBase<ResponseStateFlags> {
public:
ResponseState();
bool NotStarted() const;
bool Started() const;
bool Ended() const;
bool Canceled() const;
bool Failed() const;
bool Closed() const;
};
bool NotStarted() const;
bool Finished() const;
bool Canceled() const;
bool Failed() const;
bool Write(scoped_refptr<const net::IOBufferWithSize> buffer, bool is_last);
void Cancel();
bool SetExtraHeader(const std::string& name, const std::string& value);
void RemoveExtraHeader(const std::string& name);
void SetChunkedUpload(bool is_chunked_upload);
int StatusCode() const;
std::string StatusMessage() const;
net::HttpResponseHeaders* RawResponseHeaders() const;
uint32_t ResponseHttpVersionMajor() const;
uint32_t ResponseHttpVersionMinor() const;
void Close();
void Pin();
void Unpin();
template <typename... Args>
void EmitRequestEvent(Args... args);
template <typename... Args>
void EmitResponseEvent(Args... args);
scoped_refptr<AtomURLRequest> atom_request_;
RequestState request_state_;
ResponseState response_state_;
// Used to implement pin/unpin.
v8::Global<v8::Object> wrapper_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
DISALLOW_COPY_AND_ASSIGN(URLRequest);
};
} // namespace api
} // namespace atom
#endif // ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_

View file

@ -35,10 +35,10 @@
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/options_switches.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
@ -66,7 +66,6 @@
#include "content/public/common/context_menu_params.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request_context.h"
#include "third_party/WebKit/public/web/WebFindOptions.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"
@ -141,32 +140,6 @@ struct Converter<WindowOpenDisposition> {
}
};
template<>
struct Converter<net::HttpResponseHeaders*> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
};
template<>
struct Converter<content::SavePageType> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,

View file

@ -729,6 +729,13 @@ void Window::SetAspectRatio(double aspect_ratio, mate::Arguments* args) {
window_->SetAspectRatio(aspect_ratio, extra_size);
}
void Window::PreviewFile(const std::string& path, mate::Arguments* args) {
std::string display_name;
if (!args->GetNext(&display_name))
display_name = path;
window_->PreviewFile(path, display_name);
}
void Window::SetParentWindow(v8::Local<v8::Value> value,
mate::Arguments* args) {
if (IsModal()) {
@ -825,6 +832,7 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setFullScreen", &Window::SetFullScreen)
.SetMethod("isFullScreen", &Window::IsFullscreen)
.SetMethod("setAspectRatio", &Window::SetAspectRatio)
.SetMethod("previewFile", &Window::PreviewFile)
#if !defined(OS_WIN)
.SetMethod("setParentWindow", &Window::SetParentWindow)
#endif

View file

@ -170,6 +170,7 @@ class Window : public mate::TrackableObject<Window>,
void SetMenuBarVisibility(bool visible);
bool IsMenuBarVisible();
void SetAspectRatio(double aspect_ratio, mate::Arguments* args);
void PreviewFile(const std::string& path, mate::Arguments* args);
void SetParentWindow(v8::Local<v8::Value> value, mate::Arguments* args);
v8::Local<v8::Value> GetParentWindow() const;
std::vector<v8::Local<v8::Object>> GetChildWindows() const;

View file

@ -17,7 +17,7 @@ using content::BrowserThread;
namespace atom {
namespace {
namespace internal {
// Loads access tokens and other necessary data on the UI thread, and
// calls back to the originator on the originating thread.
@ -27,12 +27,15 @@ class TokenLoadingJob : public base::RefCountedThreadSafe<TokenLoadingJob> {
const content::AccessTokenStore::LoadAccessTokensCallback& callback)
: callback_(callback), request_context_getter_(nullptr) {}
void Run() {
BrowserThread::PostTaskAndReply(
BrowserThread::UI,
FROM_HERE,
base::Bind(&TokenLoadingJob::PerformWorkOnUIThread, this),
base::Bind(&TokenLoadingJob::RespondOnOriginatingThread, this));
void Run(AtomBrowserContext* browser_context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
request_context_getter_ = browser_context->GetRequestContext();
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (!env->GetVar("GOOGLE_API_KEY", &api_key_))
api_key_ = GOOGLEAPIS_API_KEY;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&TokenLoadingJob::RespondOnIOThread, this));
}
private:
@ -40,16 +43,7 @@ class TokenLoadingJob : public base::RefCountedThreadSafe<TokenLoadingJob> {
~TokenLoadingJob() {}
void PerformWorkOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto browser_context = AtomBrowserContext::From("", false);
request_context_getter_ = browser_context->GetRequestContext();
std::unique_ptr<base::Environment> env(base::Environment::Create());
if (!env->GetVar("GOOGLE_API_KEY", &api_key_))
api_key_ = GOOGLEAPIS_API_KEY;
}
void RespondOnOriginatingThread() {
void RespondOnIOThread() {
// Equivalent to access_token_map[kGeolocationProviderURL].
// Somehow base::string16 is causing compilation errors when used in a pair
// of std::map on Linux, this can work around it.
@ -66,9 +60,10 @@ class TokenLoadingJob : public base::RefCountedThreadSafe<TokenLoadingJob> {
std::string api_key_;
};
} // namespace
} // namespace internal
AtomAccessTokenStore::AtomAccessTokenStore() {
browser_context_ = AtomBrowserContext::From("", false);
content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
}
@ -77,8 +72,16 @@ AtomAccessTokenStore::~AtomAccessTokenStore() {
void AtomAccessTokenStore::LoadAccessTokens(
const LoadAccessTokensCallback& callback) {
scoped_refptr<TokenLoadingJob> job(new TokenLoadingJob(callback));
job->Run();
scoped_refptr<internal::TokenLoadingJob> job(
new internal::TokenLoadingJob(callback));
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&AtomAccessTokenStore::RunTokenLoadingJob,
this, base::RetainedRef(job)));
}
void AtomAccessTokenStore::RunTokenLoadingJob(
scoped_refptr<internal::TokenLoadingJob> job) {
job->Run(browser_context_.get());
}
void AtomAccessTokenStore::SaveAccessToken(const GURL& server_url,

View file

@ -9,6 +9,12 @@
namespace atom {
class AtomBrowserContext;
namespace internal {
class TokenLoadingJob;
}
class AtomAccessTokenStore : public content::AccessTokenStore {
public:
AtomAccessTokenStore();
@ -21,6 +27,9 @@ class AtomAccessTokenStore : public content::AccessTokenStore {
const base::string16& access_token) override;
private:
void RunTokenLoadingJob(scoped_refptr<internal::TokenLoadingJob> job);
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(AtomAccessTokenStore);
};

View file

@ -12,6 +12,7 @@
#include "atom/browser/browser.h"
#include "atom/browser/net/asar/asar_protocol_handler.h"
#include "atom/browser/net/atom_cert_verifier.h"
#include "atom/browser/net/atom_ct_delegate.h"
#include "atom/browser/net/atom_network_delegate.h"
#include "atom/browser/net/atom_ssl_config_service.h"
#include "atom/browser/net/atom_url_request_job_factory.h"
@ -67,10 +68,11 @@ std::string RemoveWhitespace(const std::string& str) {
} // namespace
AtomBrowserContext::AtomBrowserContext(
const std::string& partition, bool in_memory,
const base::DictionaryValue& options)
AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory,
const base::DictionaryValue& options)
: brightray::BrowserContext(partition, in_memory),
ct_delegate_(new AtomCTDelegate),
network_delegate_(new AtomNetworkDelegate),
cookie_delegate_(new AtomCookieDelegate) {
// Construct user agent string.
@ -190,7 +192,7 @@ content::PermissionManager* AtomBrowserContext::GetPermissionManager() {
}
std::unique_ptr<net::CertVerifier> AtomBrowserContext::CreateCertVerifier() {
return base::WrapUnique(new AtomCertVerifier);
return base::WrapUnique(new AtomCertVerifier(ct_delegate_.get()));
}
net::SSLConfigService* AtomBrowserContext::CreateSSLConfigService() {
@ -205,6 +207,11 @@ std::vector<std::string> AtomBrowserContext::GetCookieableSchemes() {
return default_schemes;
}
net::TransportSecurityState::RequireCTDelegate*
AtomBrowserContext::GetRequireCTDelegate() {
return ct_delegate_.get();
}
void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
pref_registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,
base::FilePath());

View file

@ -15,6 +15,7 @@
namespace atom {
class AtomBlobReader;
class AtomCTDelegate;
class AtomDownloadManagerDelegate;
class AtomNetworkDelegate;
class AtomPermissionManager;
@ -42,6 +43,8 @@ class AtomBrowserContext : public brightray::BrowserContext {
std::unique_ptr<net::CertVerifier> CreateCertVerifier() override;
net::SSLConfigService* CreateSSLConfigService() override;
std::vector<std::string> GetCookieableSchemes() override;
net::TransportSecurityState::RequireCTDelegate* GetRequireCTDelegate()
override;
// content::BrowserContext:
content::DownloadManagerDelegate* GetDownloadManagerDelegate() override;
@ -67,6 +70,7 @@ class AtomBrowserContext : public brightray::BrowserContext {
std::unique_ptr<WebViewManager> guest_manager_;
std::unique_ptr<AtomPermissionManager> permission_manager_;
std::unique_ptr<AtomBlobReader> blob_reader_;
std::unique_ptr<AtomCTDelegate> ct_delegate_;
std::string user_agent_;
bool use_cache_;

View file

@ -374,6 +374,10 @@ void NativeWindow::SetAspectRatio(double aspect_ratio,
aspect_ratio_extraSize_ = extra_size;
}
void NativeWindow::PreviewFile(const std::string& path,
const std::string& display_name) {
}
void NativeWindow::RequestToClosePage() {
bool prevent_default = false;
FOR_EACH_OBSERVER(NativeWindowObserver,

View file

@ -176,6 +176,8 @@ class NativeWindow : public base::SupportsUserData,
double GetAspectRatio();
gfx::Size GetAspectRatioExtraSize();
virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size);
virtual void PreviewFile(const std::string& path,
const std::string& display_name);
base::WeakPtr<NativeWindow> GetWeakPtr() {
return weak_factory_.GetWeakPtr();

View file

@ -55,6 +55,8 @@ class NativeWindowMac : public NativeWindow,
void SetMovable(bool movable) override;
void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size)
override;
void PreviewFile(const std::string& path, const std::string& display_name)
override;
bool IsMovable() override;
void SetMinimizable(bool minimizable) override;
bool IsMinimizable() override;

View file

@ -4,6 +4,7 @@
#include "atom/browser/native_window_mac.h"
#include <Quartz/Quartz.h>
#include <string>
#include "atom/browser/window_list.h"
@ -277,7 +278,29 @@ bool ScopedDisableResize::disable_resize_ = false;
@end
@interface AtomNSWindow : EventDispatchingWindow {
@interface AtomPreviewItem : NSObject <QLPreviewItem>
@property (nonatomic, retain) NSURL* previewItemURL;
@property (nonatomic, retain) NSString* previewItemTitle;
- (id)initWithURL:(NSURL*)url title:(NSString*)title;
@end
@implementation AtomPreviewItem
- (id)initWithURL:(NSURL*)url title:(NSString*)title {
self = [super init];
if (self) {
self.previewItemURL = url;
self.previewItemTitle = title;
}
return self;
}
@end
@interface AtomNSWindow : EventDispatchingWindow<QLPreviewPanelDataSource, QLPreviewPanelDelegate> {
@private
atom::NativeWindowMac* shell_;
bool enable_larger_than_screen_;
@ -287,6 +310,7 @@ bool ScopedDisableResize::disable_resize_ = false;
@property BOOL disableAutoHideCursor;
@property BOOL disableKeyOrMainWindow;
@property NSPoint windowButtonsOffset;
@property (nonatomic, retain) AtomPreviewItem* quickLookItem;
- (void)setShell:(atom::NativeWindowMac*)shell;
- (void)setEnableLargerThanScreen:(bool)enable;
@ -444,6 +468,36 @@ bool ScopedDisableResize::disable_resize_ = false;
return [[self contentView] superview];
}
// Quicklook methods
- (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel*)panel {
return YES;
}
- (void)beginPreviewPanelControl:(QLPreviewPanel*)panel {
panel.delegate = self;
panel.dataSource = self;
}
- (void)endPreviewPanelControl:(QLPreviewPanel*)panel {
panel.delegate = nil;
panel.dataSource = nil;
}
- (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel*)panel {
return 1;
}
- (id <QLPreviewItem>)previewPanel:(QLPreviewPanel*)panel previewItemAtIndex:(NSInteger)index {
return [self quickLookItem];
}
- (void)previewFileAtPath:(NSString*)path withName:(NSString*) fileName {
NSURL* url = [[[NSURL alloc] initFileURLWithPath:path] autorelease];
[self setQuickLookItem:[[[AtomPreviewItem alloc] initWithURL:url title:fileName] autorelease]];
[[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil];
}
@end
@interface ControlRegionView : NSView
@ -899,6 +953,13 @@ void NativeWindowMac::SetAspectRatio(double aspect_ratio,
[window_ setResizeIncrements:NSMakeSize(1.0, 1.0)];
}
void NativeWindowMac::PreviewFile(const std::string& path,
const std::string& display_name) {
NSString* path_ns = [NSString stringWithUTF8String:path.c_str()];
NSString* name_ns = [NSString stringWithUTF8String:display_name.c_str()];
[window_ previewFileAtPath:path_ns withName:name_ns];
}
void NativeWindowMac::SetMovable(bool movable) {
[window_ setMovable:movable];
}

View file

@ -327,7 +327,6 @@ NativeWindowViews::NativeWindowViews(
last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
else
last_window_state_ = ui::SHOW_STATE_NORMAL;
last_normal_bounds_ = GetBounds();
#endif
}
@ -848,7 +847,7 @@ void NativeWindowViews::SetMenu(AtomMenuModel* menu_model) {
if (!menu_bar_) {
gfx::Size content_size = GetContentSize();
menu_bar_.reset(new MenuBar);
menu_bar_.reset(new MenuBar(this));
menu_bar_->set_owned_by_client();
if (!menu_bar_autohide_) {

View file

@ -211,22 +211,6 @@ class NativeWindowViews : public NativeWindow,
ui::WindowShowState last_window_state_;
// There's an issue with restore on Windows, that sometimes causes the Window
// to receive the wrong size (#2498). To circumvent that, we keep tabs on the
// size of the window while in the normal state (not maximized, minimized or
// fullscreen), so we restore it correctly.
gfx::Rect last_normal_bounds_;
// last_normal_bounds_ may or may not require update on WM_MOVE. When a
// window is maximized, it is moved (WM_MOVE) to maximum size first and then
// sized (WM_SIZE). In this case, last_normal_bounds_ should not update. We
// keep last_normal_bounds_candidate_ as a candidate which will become valid
// last_normal_bounds_ if the moves are consecutive with no WM_SIZE event in
// between.
gfx::Rect last_normal_bounds_candidate_;
bool consecutive_moves_;
// In charge of running taskbar related APIs.
TaskbarHost taskbar_host_;

View file

@ -125,7 +125,6 @@ bool NativeWindowViews::PreHandleMSG(
return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param));
return false;
case WM_SIZE: {
consecutive_moves_ = false;
// Handle window state change.
HandleSizeEvent(w_param, l_param);
return false;
@ -135,15 +134,6 @@ bool NativeWindowViews::PreHandleMSG(
::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param);
return false;
}
case WM_MOVE: {
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
if (consecutive_moves_)
last_normal_bounds_ = last_normal_bounds_candidate_;
last_normal_bounds_candidate_ = GetBounds();
consecutive_moves_ = true;
}
return false;
}
default:
return false;
}
@ -162,35 +152,20 @@ void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) {
NotifyWindowMinimize();
break;
case SIZE_RESTORED:
if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
// Window was resized so we save it's new size.
last_normal_bounds_ = GetBounds();
} else {
switch (last_window_state_) {
case ui::SHOW_STATE_MAXIMIZED:
switch (last_window_state_) {
case ui::SHOW_STATE_MAXIMIZED:
last_window_state_ = ui::SHOW_STATE_NORMAL;
NotifyWindowUnmaximize();
break;
case ui::SHOW_STATE_MINIMIZED:
if (IsFullscreen()) {
last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
NotifyWindowEnterFullScreen();
} else {
last_window_state_ = ui::SHOW_STATE_NORMAL;
// When the window is restored we resize it to the previous known
// normal size.
SetBounds(last_normal_bounds_, false);
NotifyWindowUnmaximize();
break;
case ui::SHOW_STATE_MINIMIZED:
if (IsFullscreen()) {
last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
NotifyWindowEnterFullScreen();
} else {
last_window_state_ = ui::SHOW_STATE_NORMAL;
// When the window is restored we resize it to the previous known
// normal size.
SetBounds(last_normal_bounds_, false);
NotifyWindowRestore();
}
break;
}
NotifyWindowRestore();
}
break;
}
break;
}

View file

@ -5,9 +5,11 @@
#include "atom/browser/net/atom_cert_verifier.h"
#include "atom/browser/browser.h"
#include "atom/browser/net/atom_ct_delegate.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/net_errors.h"
#include "net/cert/cert_verify_result.h"
#include "net/cert/crl_set.h"
#include "net/cert/x509_certificate.h"
@ -28,12 +30,11 @@ void OnResult(
} // namespace
AtomCertVerifier::AtomCertVerifier()
: default_cert_verifier_(net::CertVerifier::CreateDefault()) {
}
AtomCertVerifier::AtomCertVerifier(AtomCTDelegate* ct_delegate)
: default_cert_verifier_(net::CertVerifier::CreateDefault()),
ct_delegate_(ct_delegate) {}
AtomCertVerifier::~AtomCertVerifier() {
}
AtomCertVerifier::~AtomCertVerifier() {}
void AtomCertVerifier::SetVerifyProc(const VerifyProc& proc) {
verify_proc_ = proc;
@ -48,9 +49,15 @@ int AtomCertVerifier::Verify(
const net::BoundNetLog& net_log) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (verify_proc_.is_null())
if (verify_proc_.is_null()) {
ct_delegate_->ClearCTExcludedHostsList();
return default_cert_verifier_->Verify(
params, crl_set, verify_result, callback, out_req, net_log);
}
verify_result->Reset();
verify_result->verified_cert = params.certificate();
ct_delegate_->AddCTExcludedHost(params.hostname());
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,

View file

@ -12,9 +12,11 @@
namespace atom {
class AtomCTDelegate;
class AtomCertVerifier : public net::CertVerifier {
public:
AtomCertVerifier();
explicit AtomCertVerifier(AtomCTDelegate* ct_delegate);
virtual ~AtomCertVerifier();
using VerifyProc =
@ -37,6 +39,7 @@ class AtomCertVerifier : public net::CertVerifier {
private:
VerifyProc verify_proc_;
std::unique_ptr<net::CertVerifier> default_cert_verifier_;
AtomCTDelegate* ct_delegate_;
DISALLOW_COPY_AND_ASSIGN(AtomCertVerifier);
};

View file

@ -0,0 +1,34 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/atom_ct_delegate.h"
#include "content/public/browser/browser_thread.h"
namespace atom {
AtomCTDelegate::AtomCTDelegate() {}
AtomCTDelegate::~AtomCTDelegate() {}
void AtomCTDelegate::AddCTExcludedHost(const std::string& host) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
ct_excluded_hosts_.insert(host);
}
void AtomCTDelegate::ClearCTExcludedHostsList() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
ct_excluded_hosts_.clear();
}
AtomCTDelegate::CTRequirementLevel AtomCTDelegate::IsCTRequiredForHost(
const std::string& host) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!ct_excluded_hosts_.empty() &&
(ct_excluded_hosts_.find(host) != ct_excluded_hosts_.end()))
return CTRequirementLevel::NOT_REQUIRED;
return CTRequirementLevel::DEFAULT;
}
} // namespace atom

View file

@ -0,0 +1,33 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ATOM_CT_DELEGATE_H_
#define ATOM_BROWSER_NET_ATOM_CT_DELEGATE_H_
#include <set>
#include <string>
#include "net/http/transport_security_state.h"
namespace atom {
class AtomCTDelegate : public net::TransportSecurityState::RequireCTDelegate {
public:
AtomCTDelegate();
~AtomCTDelegate() override;
void AddCTExcludedHost(const std::string& host);
void ClearCTExcludedHostsList();
// net::TransportSecurityState::RequireCTDelegate:
CTRequirementLevel IsCTRequiredForHost(const std::string& host) override;
private:
std::set<std::string> ct_excluded_hosts_;
DISALLOW_COPY_AND_ASSIGN(AtomCTDelegate);
};
} // namespace atom
#endif // ATOM_BROWSER_NET_ATOM_CT_DELEGATE_H_

View file

@ -0,0 +1,422 @@
// Copyright (c) 2016 GitHub, Inc.
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/atom_url_request.h"
#include <string>
#include "atom/browser/api/atom_api_url_request.h"
#include "atom/browser/atom_browser_context.h"
#include "base/callback.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/elements_upload_data_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/upload_bytes_element_reader.h"
namespace {
const int kBufferSize = 4096;
} // namespace
namespace atom {
namespace internal {
class UploadOwnedIOBufferElementReader : public net::UploadBytesElementReader {
public:
explicit UploadOwnedIOBufferElementReader(
scoped_refptr<const net::IOBufferWithSize> buffer)
: net::UploadBytesElementReader(buffer->data(), buffer->size()),
buffer_(buffer) {}
~UploadOwnedIOBufferElementReader() override {}
static UploadOwnedIOBufferElementReader* CreateWithBuffer(
scoped_refptr<const net::IOBufferWithSize> buffer) {
return new UploadOwnedIOBufferElementReader(std::move(buffer));
}
private:
scoped_refptr<const net::IOBuffer> buffer_;
DISALLOW_COPY_AND_ASSIGN(UploadOwnedIOBufferElementReader);
};
} // namespace internal
AtomURLRequest::AtomURLRequest(api::URLRequest* delegate)
: delegate_(delegate),
is_chunked_upload_(false),
response_read_buffer_(new net::IOBuffer(kBufferSize)) {}
AtomURLRequest::~AtomURLRequest() {
DCHECK(!request_context_getter_);
DCHECK(!request_);
}
scoped_refptr<AtomURLRequest> AtomURLRequest::Create(
AtomBrowserContext* browser_context,
const std::string& method,
const std::string& url,
api::URLRequest* delegate) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(browser_context);
DCHECK(!url.empty());
DCHECK(delegate);
if (!browser_context || url.empty() || !delegate) {
return nullptr;
}
auto request_context_getter = browser_context->url_request_context_getter();
DCHECK(request_context_getter);
if (!request_context_getter) {
return nullptr;
}
scoped_refptr<AtomURLRequest> atom_url_request(new AtomURLRequest(delegate));
if (content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoInitialize, atom_url_request,
request_context_getter, method, url))) {
return atom_url_request;
}
return nullptr;
}
void AtomURLRequest::Terminate() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
delegate_ = nullptr;
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoTerminate, this));
}
void AtomURLRequest::DoInitialize(
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
const std::string& method,
const std::string& url) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DCHECK(request_context_getter);
request_context_getter_ = request_context_getter;
request_context_getter_->AddObserver(this);
auto context = request_context_getter_->GetURLRequestContext();
if (!context) {
// Called after shutdown.
DoCancelWithError("Cannot start a request after shutdown.", true);
return;
}
DCHECK(context);
request_ = context->CreateRequest(
GURL(url), net::RequestPriority::DEFAULT_PRIORITY, this);
if (!request_) {
DoCancelWithError("Failed to create a net::URLRequest.", true);
return;
}
request_->set_method(method);
}
void AtomURLRequest::DoTerminate() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
request_.reset();
if (request_context_getter_) {
request_context_getter_->RemoveObserver(this);
request_context_getter_ = nullptr;
}
}
bool AtomURLRequest::Write(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
return content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoWriteBuffer, this, buffer, is_last));
}
void AtomURLRequest::SetChunkedUpload(bool is_chunked_upload) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// The method can be called only before switching to multi-threaded mode,
// i.e. before the first call to write.
// So it is safe to change the object in the UI thread.
is_chunked_upload_ = is_chunked_upload;
}
void AtomURLRequest::Cancel() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::BrowserThread::PostTask(content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoCancel, this));
}
void AtomURLRequest::SetExtraHeader(const std::string& name,
const std::string& value) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoSetExtraHeader, this, name, value));
}
void AtomURLRequest::RemoveExtraHeader(const std::string& name) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoRemoveExtraHeader, this, name));
}
void AtomURLRequest::PassLoginInformation(
const base::string16& username,
const base::string16& password) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (username.empty() || password.empty()) {
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoCancelAuth, this));
} else {
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&AtomURLRequest::DoSetAuth, this, username, password));
}
}
void AtomURLRequest::DoWriteBuffer(
scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
if (is_chunked_upload_) {
// Chunked encoding case.
bool first_call = false;
if (!chunked_stream_writer_) {
std::unique_ptr<net::ChunkedUploadDataStream> chunked_stream(
new net::ChunkedUploadDataStream(0));
chunked_stream_writer_ = chunked_stream->CreateWriter();
request_->set_upload(std::move(chunked_stream));
first_call = true;
}
if (buffer)
// Non-empty buffer.
chunked_stream_writer_->AppendData(buffer->data(), buffer->size(),
is_last);
else if (is_last)
// Empty buffer and last chunk, i.e. request.end().
chunked_stream_writer_->AppendData(nullptr, 0, true);
if (first_call) {
request_->Start();
}
} else {
if (buffer) {
// Handling potential empty buffers.
using internal::UploadOwnedIOBufferElementReader;
auto element_reader =
UploadOwnedIOBufferElementReader::CreateWithBuffer(std::move(buffer));
upload_element_readers_.push_back(
std::unique_ptr<net::UploadElementReader>(element_reader));
}
if (is_last) {
auto elements_upload_data_stream = new net::ElementsUploadDataStream(
std::move(upload_element_readers_), 0);
request_->set_upload(
std::unique_ptr<net::UploadDataStream>(elements_upload_data_stream));
request_->Start();
}
}
}
void AtomURLRequest::DoCancel() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (request_) {
request_->Cancel();
}
DoTerminate();
}
void AtomURLRequest::DoSetExtraHeader(const std::string& name,
const std::string& value) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
request_->SetExtraRequestHeaderByName(name, value, true);
}
void AtomURLRequest::DoRemoveExtraHeader(const std::string& name) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
request_->RemoveRequestHeaderByName(name);
}
void AtomURLRequest::DoSetAuth(const base::string16& username,
const base::string16& password) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
request_->SetAuth(net::AuthCredentials(username, password));
}
void AtomURLRequest::DoCancelAuth() const {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
request_->CancelAuth();
}
void AtomURLRequest::DoCancelWithError(const std::string& error,
bool isRequestError) {
DoCancel();
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomURLRequest::InformDelegateErrorOccured, this, error,
isRequestError));
}
void AtomURLRequest::OnAuthRequired(net::URLRequest* request,
net::AuthChallengeInfo* auth_info) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomURLRequest::InformDelegateAuthenticationRequired, this,
scoped_refptr<net::AuthChallengeInfo>(auth_info)));
}
void AtomURLRequest::OnResponseStarted(net::URLRequest* request) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
DCHECK_EQ(request, request_.get());
scoped_refptr<net::HttpResponseHeaders> response_headers =
request->response_headers();
const auto& status = request_->status();
if (status.is_success()) {
// Success or pending trigger a Read.
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomURLRequest::InformDelegateResponseStarted, this,
response_headers));
ReadResponse();
} else if (status.status() == net::URLRequestStatus::Status::FAILED) {
// Report error on Start.
DoCancelWithError(net::ErrorToString(status.ToNetError()), true);
}
// We don't report an error is the request is canceled.
}
void AtomURLRequest::ReadResponse() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
int bytes_read = -1;
if (request_->Read(response_read_buffer_.get(), kBufferSize, &bytes_read)) {
OnReadCompleted(request_.get(), bytes_read);
}
}
void AtomURLRequest::OnReadCompleted(net::URLRequest* request, int bytes_read) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (!request_) {
return;
}
DCHECK_EQ(request, request_.get());
const auto status = request_->status();
bool response_error = false;
bool data_ended = false;
bool data_transfer_error = false;
do {
if (!status.is_success()) {
response_error = true;
break;
}
if (bytes_read == 0) {
data_ended = true;
break;
}
if (bytes_read < 0 || !CopyAndPostBuffer(bytes_read)) {
data_transfer_error = true;
break;
}
} while (
request_->Read(response_read_buffer_.get(), kBufferSize, &bytes_read));
if (response_error) {
DoCancelWithError(net::ErrorToString(status.ToNetError()), false);
} else if (data_ended) {
content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomURLRequest::InformDelegateResponseCompleted, this));
DoTerminate();
} else if (data_transfer_error) {
// We abort the request on corrupted data transfer.
DoCancelWithError("Failed to transfer data from IO to UI thread.", false);
}
}
void AtomURLRequest::OnContextShuttingDown() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
DoCancel();
}
bool AtomURLRequest::CopyAndPostBuffer(int bytes_read) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
// data is only a wrapper for the asynchronous response_read_buffer_.
// Make a deep copy of payload and transfer ownership to the UI thread.
auto buffer_copy = new net::IOBufferWithSize(bytes_read);
memcpy(buffer_copy->data(), response_read_buffer_->data(), bytes_read);
return content::BrowserThread::PostTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&AtomURLRequest::InformDelegateResponseData, this,
buffer_copy));
}
void AtomURLRequest::InformDelegateAuthenticationRequired(
scoped_refptr<net::AuthChallengeInfo> auth_info) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (delegate_)
delegate_->OnAuthenticationRequired(auth_info);
}
void AtomURLRequest::InformDelegateResponseStarted(
scoped_refptr<net::HttpResponseHeaders> response_headers) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (delegate_)
delegate_->OnResponseStarted(response_headers);
}
void AtomURLRequest::InformDelegateResponseData(
scoped_refptr<net::IOBufferWithSize> data) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
// Transfer ownership of the data buffer, data will be released
// by the delegate's OnResponseData.
if (delegate_)
delegate_->OnResponseData(data);
}
void AtomURLRequest::InformDelegateResponseCompleted() const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (delegate_)
delegate_->OnResponseCompleted();
}
void AtomURLRequest::InformDelegateErrorOccured(const std::string& error,
bool isRequestError) const {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (delegate_)
delegate_->OnError(error, isRequestError);
}
} // namespace atom

View file

@ -0,0 +1,104 @@
// Copyright (c) 2016 GitHub, Inc.
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_
#define ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_
#include <string>
#include <vector>
#include "atom/browser/api/atom_api_url_request.h"
#include "atom/browser/atom_browser_context.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "net/base/auth.h"
#include "net/base/chunked_upload_data_stream.h"
#include "net/base/io_buffer.h"
#include "net/base/upload_element_reader.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context_getter_observer.h"
namespace atom {
class AtomURLRequest : public base::RefCountedThreadSafe<AtomURLRequest>,
public net::URLRequest::Delegate,
public net::URLRequestContextGetterObserver {
public:
static scoped_refptr<AtomURLRequest> Create(
AtomBrowserContext* browser_context,
const std::string& method,
const std::string& url,
api::URLRequest* delegate);
void Terminate();
bool Write(scoped_refptr<const net::IOBufferWithSize> buffer, bool is_last);
void SetChunkedUpload(bool is_chunked_upload);
void Cancel();
void SetExtraHeader(const std::string& name, const std::string& value) const;
void RemoveExtraHeader(const std::string& name) const;
void PassLoginInformation(const base::string16& username,
const base::string16& password) const;
protected:
// Overrides of net::URLRequest::Delegate
void OnAuthRequired(net::URLRequest* request,
net::AuthChallengeInfo* auth_info) override;
void OnResponseStarted(net::URLRequest* request) override;
void OnReadCompleted(net::URLRequest* request, int bytes_read) override;
// Overrides of net::URLRequestContextGetterObserver
void OnContextShuttingDown() override;
private:
friend class base::RefCountedThreadSafe<AtomURLRequest>;
explicit AtomURLRequest(api::URLRequest* delegate);
~AtomURLRequest() override;
void DoInitialize(scoped_refptr<net::URLRequestContextGetter>,
const std::string& method,
const std::string& url);
void DoTerminate();
void DoWriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer,
bool is_last);
void DoCancel();
void DoSetExtraHeader(const std::string& name,
const std::string& value) const;
void DoRemoveExtraHeader(const std::string& name) const;
void DoSetAuth(const base::string16& username,
const base::string16& password) const;
void DoCancelAuth() const;
void DoCancelWithError(const std::string& error, bool isRequestError);
void ReadResponse();
bool CopyAndPostBuffer(int bytes_read);
void InformDelegateAuthenticationRequired(
scoped_refptr<net::AuthChallengeInfo> auth_info) const;
void InformDelegateResponseStarted(
scoped_refptr<net::HttpResponseHeaders>) const;
void InformDelegateResponseData(
scoped_refptr<net::IOBufferWithSize> data) const;
void InformDelegateResponseCompleted() const;
void InformDelegateErrorOccured(const std::string& error,
bool isRequestError) const;
api::URLRequest* delegate_;
std::unique_ptr<net::URLRequest> request_;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
bool is_chunked_upload_;
std::unique_ptr<net::ChunkedUploadDataStream> chunked_stream_;
std::unique_ptr<net::ChunkedUploadDataStream::Writer> chunked_stream_writer_;
std::vector<std::unique_ptr<net::UploadElementReader>>
upload_element_readers_;
scoped_refptr<net::IOBuffer> response_read_buffer_;
DISALLOW_COPY_AND_ASSIGN(AtomURLRequest);
};
} // namespace atom
#endif // ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_

View file

@ -47,9 +47,10 @@ void GetMenuBarColor(SkColor* enabled, SkColor* disabled, SkColor* highlight,
} // namespace
MenuBar::MenuBar()
MenuBar::MenuBar(NativeWindow* window)
: background_color_(kDefaultColor),
menu_model_(NULL) {
menu_model_(NULL),
window_(window) {
UpdateMenuBarColor();
SetLayoutManager(new views::BoxLayout(
views::BoxLayout::kHorizontal, 0, 0, 0));
@ -142,6 +143,9 @@ void MenuBar::OnMenuButtonClicked(views::MenuButton* source,
if (!menu_model_)
return;
if (!window_->IsFocused())
window_->Focus(true);
int id = source->tag();
AtomMenuModel::ItemType type = menu_model_->GetTypeAt(id);
if (type != AtomMenuModel::TYPE_SUBMENU) {

View file

@ -5,6 +5,7 @@
#ifndef ATOM_BROWSER_UI_VIEWS_MENU_BAR_H_
#define ATOM_BROWSER_UI_VIEWS_MENU_BAR_H_
#include "atom/browser/native_window.h"
#include "atom/browser/ui/atom_menu_model.h"
#include "ui/views/controls/button/menu_button_listener.h"
#include "ui/views/view.h"
@ -20,7 +21,7 @@ class MenuDelegate;
class MenuBar : public views::View,
public views::MenuButtonListener {
public:
MenuBar();
explicit MenuBar(NativeWindow* window);
virtual ~MenuBar();
// Replaces current menu with a new one.
@ -66,6 +67,7 @@ class MenuBar : public views::View,
SkColor hover_color_;
#endif
NativeWindow* window_;
AtomMenuModel* menu_model_;
DISALLOW_COPY_AND_ASSIGN(MenuBar);

View file

@ -52,10 +52,6 @@ SubmenuButton::SubmenuButton(const base::string16& title,
SetHasInkDrop(true);
set_ink_drop_base_color(
color_utils::BlendTowardOppositeLuma(background_color_, 0x61));
set_request_focus_on_press(true);
SetFocusForPlatform();
SetFocusPainter(nullptr);
}
SubmenuButton::~SubmenuButton() {

View file

@ -2,24 +2,20 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "atom/common/api/atom_api_clipboard.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "base/strings/utf_string_conversions.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
#include "ui/gfx/image/image.h"
#include "atom/common/node_includes.h"
namespace {
namespace atom {
ui::ClipboardType GetClipboardType(mate::Arguments* args) {
namespace api {
ui::ClipboardType Clipboard::GetClipboardType(mate::Arguments* args) {
std::string type;
if (args->GetNext(&type) && type == "selection")
return ui::CLIPBOARD_TYPE_SELECTION;
@ -27,7 +23,7 @@ ui::ClipboardType GetClipboardType(mate::Arguments* args) {
return ui::CLIPBOARD_TYPE_COPY_PASTE;
}
std::vector<base::string16> AvailableFormats(mate::Arguments* args) {
std::vector<base::string16> Clipboard::AvailableFormats(mate::Arguments* args) {
std::vector<base::string16> format_types;
bool ignore;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
@ -35,14 +31,14 @@ std::vector<base::string16> AvailableFormats(mate::Arguments* args) {
return format_types;
}
bool Has(const std::string& format_string, mate::Arguments* args) {
bool Clipboard::Has(const std::string& format_string, mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
return clipboard->IsFormatAvailable(format, GetClipboardType(args));
}
std::string Read(const std::string& format_string,
mate::Arguments* args) {
std::string Clipboard::Read(const std::string& format_string,
mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
ui::Clipboard::FormatType format(ui::Clipboard::GetFormatType(format_string));
@ -51,8 +47,7 @@ std::string Read(const std::string& format_string,
return data;
}
void Write(const mate::Dictionary& data,
mate::Arguments* args) {
void Clipboard::Write(const mate::Dictionary& data, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
base::string16 text, html, bookmark;
gfx::Image image;
@ -76,7 +71,7 @@ void Write(const mate::Dictionary& data,
writer.WriteImage(image.AsBitmap());
}
base::string16 ReadText(mate::Arguments* args) {
base::string16 Clipboard::ReadText(mate::Arguments* args) {
base::string16 data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
auto type = GetClipboardType(args);
@ -92,24 +87,24 @@ base::string16 ReadText(mate::Arguments* args) {
return data;
}
void WriteText(const base::string16& text, mate::Arguments* args) {
void Clipboard::WriteText(const base::string16& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteText(text);
}
base::string16 ReadRtf(mate::Arguments* args) {
base::string16 Clipboard::ReadRtf(mate::Arguments* args) {
std::string data;
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadRTF(GetClipboardType(args), &data);
return base::UTF8ToUTF16(data);
}
void WriteRtf(const std::string& text, mate::Arguments* args) {
void Clipboard::WriteRtf(const std::string& text, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteRTF(text);
}
base::string16 ReadHtml(mate::Arguments* args) {
base::string16 Clipboard::ReadHtml(mate::Arguments* args) {
base::string16 data;
base::string16 html;
std::string url;
@ -121,12 +116,12 @@ base::string16 ReadHtml(mate::Arguments* args) {
return data;
}
void WriteHtml(const base::string16& html, mate::Arguments* args) {
void Clipboard::WriteHtml(const base::string16& html, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteHTML(html, std::string());
}
v8::Local<v8::Value> ReadBookmark(mate::Arguments* args) {
v8::Local<v8::Value> Clipboard::ReadBookmark(mate::Arguments* args) {
base::string16 title;
std::string url;
mate::Dictionary dict = mate::Dictionary::CreateEmpty(args->isolate());
@ -137,51 +132,65 @@ v8::Local<v8::Value> ReadBookmark(mate::Arguments* args) {
return dict.GetHandle();
}
void WriteBookmark(const base::string16& title, const std::string& url,
mate::Arguments* args) {
void Clipboard::WriteBookmark(const base::string16& title,
const std::string& url,
mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteBookmark(title, url);
}
gfx::Image ReadImage(mate::Arguments* args) {
gfx::Image Clipboard::ReadImage(mate::Arguments* args) {
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
SkBitmap bitmap = clipboard->ReadImage(GetClipboardType(args));
return gfx::Image::CreateFrom1xBitmap(bitmap);
}
void WriteImage(const gfx::Image& image, mate::Arguments* args) {
void Clipboard::WriteImage(const gfx::Image& image, mate::Arguments* args) {
ui::ScopedClipboardWriter writer(GetClipboardType(args));
writer.WriteImage(image.AsBitmap());
}
void Clear(mate::Arguments* args) {
#if !defined(OS_MACOSX)
void Clipboard::WriteFindText(const base::string16& text) {}
base::string16 Clipboard::ReadFindText() { return base::string16(); }
#endif
void Clipboard::Clear(mate::Arguments* args) {
ui::Clipboard::GetForCurrentThread()->Clear(GetClipboardType(args));
}
} // namespace api
} // namespace atom
namespace {
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
dict.SetMethod("availableFormats", &AvailableFormats);
dict.SetMethod("has", &Has);
dict.SetMethod("read", &Read);
dict.SetMethod("write", &Write);
dict.SetMethod("readText", &ReadText);
dict.SetMethod("writeText", &WriteText);
dict.SetMethod("readRTF", &ReadRtf);
dict.SetMethod("writeRTF", &WriteRtf);
dict.SetMethod("readHTML", &ReadHtml);
dict.SetMethod("writeHTML", &WriteHtml);
dict.SetMethod("readBookmark", &ReadBookmark);
dict.SetMethod("writeBookmark", &WriteBookmark);
dict.SetMethod("readImage", &ReadImage);
dict.SetMethod("writeImage", &WriteImage);
dict.SetMethod("clear", &Clear);
dict.SetMethod("availableFormats", &atom::api::Clipboard::AvailableFormats);
dict.SetMethod("has", &atom::api::Clipboard::Has);
dict.SetMethod("read", &atom::api::Clipboard::Read);
dict.SetMethod("write", &atom::api::Clipboard::Write);
dict.SetMethod("readText", &atom::api::Clipboard::ReadText);
dict.SetMethod("writeText", &atom::api::Clipboard::WriteText);
dict.SetMethod("readRTF", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRTF", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHTML", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHTML", &atom::api::Clipboard::WriteHtml);
dict.SetMethod("readBookmark", &atom::api::Clipboard::ReadBookmark);
dict.SetMethod("writeBookmark", &atom::api::Clipboard::WriteBookmark);
dict.SetMethod("readImage", &atom::api::Clipboard::ReadImage);
dict.SetMethod("writeImage", &atom::api::Clipboard::WriteImage);
dict.SetMethod("readFindText", &atom::api::Clipboard::ReadFindText);
dict.SetMethod("writeFindText", &atom::api::Clipboard::WriteFindText);
dict.SetMethod("clear", &atom::api::Clipboard::Clear);
// TODO(kevinsawicki): Remove in 2.0, deprecate before then with warnings
dict.SetMethod("readRtf", &ReadRtf);
dict.SetMethod("writeRtf", &WriteRtf);
dict.SetMethod("readHtml", &ReadHtml);
dict.SetMethod("writeHtml", &WriteHtml);
dict.SetMethod("readRtf", &atom::api::Clipboard::ReadRtf);
dict.SetMethod("writeRtf", &atom::api::Clipboard::WriteRtf);
dict.SetMethod("readHtml", &atom::api::Clipboard::ReadHtml);
dict.SetMethod("writeHtml", &atom::api::Clipboard::WriteHtml);
}
} // namespace

View file

@ -0,0 +1,59 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_COMMON_API_ATOM_API_CLIPBOARD_H_
#define ATOM_COMMON_API_ATOM_API_CLIPBOARD_H_
#include <string>
#include <vector>
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/gfx/image/image.h"
namespace atom {
namespace api {
class Clipboard {
public:
static ui::ClipboardType GetClipboardType(mate::Arguments* args);
static std::vector<base::string16> AvailableFormats(mate::Arguments* args);
static bool Has(const std::string& format_string, mate::Arguments* args);
static void Clear(mate::Arguments* args);
static std::string Read(const std::string& format_string,
mate::Arguments* args);
static void Write(const mate::Dictionary& data, mate::Arguments* args);
static base::string16 ReadText(mate::Arguments* args);
static void WriteText(const base::string16& text, mate::Arguments* args);
static base::string16 ReadRtf(mate::Arguments* args);
static void WriteRtf(const std::string& text, mate::Arguments* args);
static base::string16 ReadHtml(mate::Arguments* args);
static void WriteHtml(const base::string16& html, mate::Arguments* args);
static v8::Local<v8::Value> ReadBookmark(mate::Arguments* args);
static void WriteBookmark(const base::string16& title,
const std::string& url,
mate::Arguments* args);
static gfx::Image ReadImage(mate::Arguments* args);
static void WriteImage(const gfx::Image& image, mate::Arguments* args);
static base::string16 ReadFindText();
static void WriteFindText(const base::string16& text);
private:
DISALLOW_COPY_AND_ASSIGN(Clipboard);
};
} // namespace api
} // namespace atom
#endif // ATOM_COMMON_API_ATOM_API_CLIPBOARD_H_

View file

@ -0,0 +1,24 @@
// Copyright (c) 2016 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/common/api/atom_api_clipboard.h"
#include "base/strings/sys_string_conversions.h"
#include "ui/base/cocoa/find_pasteboard.h"
namespace atom {
namespace api {
void Clipboard::WriteFindText(const base::string16& text) {
NSString* text_ns = base::SysUTF16ToNSString(text);
[[FindPasteboard sharedInstance] setFindText:text_ns];
}
base::string16 Clipboard::ReadFindText() {
return GetFindPboardText();
}
} // namespace api
} // namespace atom

View file

@ -92,6 +92,11 @@ void TakeHeapSnapshot(v8::Isolate* isolate) {
isolate->GetHeapProfiler()->TakeHeapSnapshot();
}
void RequestGarbageCollectionForTesting(v8::Isolate* isolate) {
isolate->RequestGarbageCollectionForTesting(
v8::Isolate::GarbageCollectionType::kFullGarbageCollection);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
mate::Dictionary dict(context->GetIsolate(), exports);
@ -105,6 +110,8 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
dict.SetMethod("createIDWeakMap", &atom::api::KeyWeakMap<int32_t>::Create);
dict.SetMethod("createDoubleIDWeakMap",
&atom::api::KeyWeakMap<std::pair<int64_t, int32_t>>::Create);
dict.SetMethod("requestGarbageCollectionForTesting",
&RequestGarbageCollectionForTesting);
}
} // namespace

View file

@ -11,16 +11,16 @@ namespace mate {
namespace internal {
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args) {
v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const char* method,
ValueVector* args) {
// Perform microtask checkpoint after running JavaScript.
v8::MicrotasksScope script_scope(
isolate, v8::MicrotasksScope::kRunMicrotasks);
v8::MicrotasksScope script_scope(isolate,
v8::MicrotasksScope::kRunMicrotasks);
// Use node::MakeCallback to call the callback, and it will also run pending
// tasks in Node.js.
return node::MakeCallback(
isolate, obj, "emit", args->size(), &args->front());
return node::MakeCallback(isolate, obj, method, args->size(), &args->front());
}
} // namespace internal

View file

@ -15,37 +15,50 @@ namespace internal {
using ValueVector = std::vector<v8::Local<v8::Value>>;
v8::Local<v8::Value> CallEmitWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
ValueVector* args);
v8::Local<v8::Value> CallMethodWithArgs(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const char* method,
ValueVector* args);
} // namespace internal
// obj.emit.apply(obj, name, args...);
// The caller is responsible of allocating a HandleScope.
template<typename StringType, typename... Args>
template <typename StringType>
v8::Local<v8::Value> EmitEvent(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const StringType& name,
const internal::ValueVector& args) {
internal::ValueVector concatenated_args = { StringToV8(isolate, name) };
internal::ValueVector concatenated_args = {StringToV8(isolate, name)};
concatenated_args.reserve(1 + args.size());
concatenated_args.insert(concatenated_args.end(), args.begin(), args.end());
return internal::CallEmitWithArgs(isolate, obj, &concatenated_args);
return internal::CallMethodWithArgs(isolate, obj, "emit", &concatenated_args);
}
// obj.emit(name, args...);
// The caller is responsible of allocating a HandleScope.
template<typename StringType, typename... Args>
template <typename StringType, typename... Args>
v8::Local<v8::Value> EmitEvent(v8::Isolate* isolate,
v8::Local<v8::Object> obj,
const StringType& name,
const Args&... args) {
internal::ValueVector converted_args = {
StringToV8(isolate, name),
StringToV8(isolate, name), ConvertToV8(isolate, args)...,
};
return internal::CallMethodWithArgs(isolate, obj, "emit", &converted_args);
}
// obj.custom_emit(args...)
template <typename... Args>
v8::Local<v8::Value> CustomEmit(v8::Isolate* isolate,
v8::Local<v8::Object> object,
const char* custom_emit,
const Args&... args) {
internal::ValueVector converted_args = {
ConvertToV8(isolate, args)...,
};
return internal::CallEmitWithArgs(isolate, obj, &converted_args);
return internal::CallMethodWithArgs(isolate, object, custom_emit,
&converted_args);
}
} // namespace mate

View file

@ -10,6 +10,7 @@
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "native_mate/dictionary.h"
#include "net/base/upload_bytes_element_reader.h"
@ -58,6 +59,31 @@ v8::Local<v8::Value> Converter<scoped_refptr<net::X509Certificate>>::ToV8(
return dict.GetHandle();
}
// static
v8::Local<v8::Value> Converter<net::HttpResponseHeaders*>::ToV8(
v8::Isolate* isolate,
net::HttpResponseHeaders* headers) {
base::DictionaryValue response_headers;
if (headers) {
size_t iter = 0;
std::string key;
std::string value;
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
key = base::ToLowerASCII(key);
if (response_headers.HasKey(key)) {
base::ListValue* values = nullptr;
if (response_headers.GetList(key, &values))
values->AppendString(value);
} else {
std::unique_ptr<base::ListValue> values(new base::ListValue());
values->AppendString(value);
response_headers.Set(key, std::move(values));
}
}
}
return ConvertToV8(isolate, response_headers);
}
} // namespace mate
namespace atom {

View file

@ -17,6 +17,7 @@ namespace net {
class AuthChallengeInfo;
class URLRequest;
class X509Certificate;
class HttpResponseHeaders;
}
namespace mate {
@ -33,6 +34,12 @@ struct Converter<scoped_refptr<net::X509Certificate>> {
const scoped_refptr<net::X509Certificate>& val);
};
template <>
struct Converter<net::HttpResponseHeaders*> {
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
net::HttpResponseHeaders* headers);
};
} // namespace mate
namespace atom {

View file

@ -39,6 +39,7 @@ REFERENCE_MODULE(atom_browser_debugger);
REFERENCE_MODULE(atom_browser_desktop_capturer);
REFERENCE_MODULE(atom_browser_download_item);
REFERENCE_MODULE(atom_browser_menu);
REFERENCE_MODULE(atom_browser_net);
REFERENCE_MODULE(atom_browser_power_monitor);
REFERENCE_MODULE(atom_browser_power_save_blocker);
REFERENCE_MODULE(atom_browser_protocol);

View file

@ -140,17 +140,44 @@ void WebFrame::RegisterURLSchemeAsBypassingCSP(const std::string& scheme) {
blink::WebString::fromUTF8(scheme));
}
void WebFrame::RegisterURLSchemeAsPrivileged(const std::string& scheme) {
void WebFrame::RegisterURLSchemeAsPrivileged(const std::string& scheme,
mate::Arguments* args) {
// Read optional flags
bool secure = true;
bool bypassCSP = true;
bool allowServiceWorkers = true;
bool supportFetchAPI = true;
bool corsEnabled = true;
if (args->Length() == 2) {
mate::Dictionary options;
if (args->GetNext(&options)) {
options.Get("secure", &secure);
options.Get("bypassCSP", &bypassCSP);
options.Get("allowServiceWorkers", &allowServiceWorkers);
options.Get("supportFetchAPI", &supportFetchAPI);
options.Get("corsEnabled", &corsEnabled);
}
}
// Register scheme to privileged list (https, wss, data, chrome-extension)
blink::WebString privileged_scheme(blink::WebString::fromUTF8(scheme));
blink::WebSecurityPolicy::registerURLSchemeAsSecure(privileged_scheme);
blink::WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
privileged_scheme);
blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
privileged_scheme);
blink::WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI(
privileged_scheme);
blink::WebSecurityPolicy::registerURLSchemeAsCORSEnabled(privileged_scheme);
if (secure) {
blink::WebSecurityPolicy::registerURLSchemeAsSecure(privileged_scheme);
}
if (bypassCSP) {
blink::WebSecurityPolicy::registerURLSchemeAsBypassingContentSecurityPolicy(
privileged_scheme);
}
if (allowServiceWorkers) {
blink::WebSecurityPolicy::registerURLSchemeAsAllowingServiceWorkers(
privileged_scheme);
}
if (supportFetchAPI) {
blink::WebSecurityPolicy::registerURLSchemeAsSupportingFetchAPI(
privileged_scheme);
}
if (corsEnabled) {
blink::WebSecurityPolicy::registerURLSchemeAsCORSEnabled(privileged_scheme);
}
}
void WebFrame::InsertText(const std::string& text) {

View file

@ -63,7 +63,8 @@ class WebFrame : public mate::Wrappable<WebFrame> {
void RegisterURLSchemeAsSecure(const std::string& scheme);
void RegisterURLSchemeAsBypassingCSP(const std::string& scheme);
void RegisterURLSchemeAsPrivileged(const std::string& scheme);
void RegisterURLSchemeAsPrivileged(const std::string& scheme,
mate::Arguments* args);
// Editing.
void InsertText(const std::string& text);

View file

@ -0,0 +1,27 @@
# Plateformes supportées
Les plateformes suivantes sont supportées par Electron:
### macOS
Seulement les binaires en 64bit sont fournis sur macOS, et la version minimale de macOS suportée est macOS 10.9.
### Windows
Windows 7 et suivants sont supportés, les systèmes d'exploitation plus ancien ne sont pas supporté
(et ne marchent pas).
Les binaires `ia32` (`x86`) et `x64` (`amd64`) sont fournis pour Windows.
Veuillez noter que la version `ARM` de Windows n'est pas supporté à ce jour.
### Linux
Les binaires précompilés `ia32` (`i686`) et `x64` (`amd64`) d'Electron sont compilés sous
Ubuntu 12.04, le binaire `arm` est compilé à partir d'une version ARM v7 hard-float ABI et
NEON pour Debian Wheezy.
Le binaire précompilé peut tourner sur une distribution si la distribution contient les librairies liées à Electron, sur la plateforme de compilation. Donc il est ganranti de pouvoir le faire marcher seulement sur Ubuntu 12.04, mais les plateformes suivantes sont aussi vérifiées comme capable de faire marcher la version précompilé des binaires d'Electron :
* Ubuntu 12.04 et suivantes
* Fedora 21
* Debian 8

View file

@ -2,13 +2,29 @@
> 키보드 단축키를 정의합니다.
Accelerator는 `+` 문자를 통해 여러 혼합키와 키코드를 결합할 수 있습니다.
Accelerator 는 `+` 문자로 결합된 여러 수식어와 키 코드를 포함할 수 있는
문자열입니다. 그리고 애플리케이션의 키보드 단축키를 정의하는데 사용됩니다.
예시:
* `CommandOrControl+A`
* `CommandOrControl+Shift+Z`
단축키는 [`globalShortcut`](global-shortcut.md) 모듈의
[`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
메소드로 등록됩니다. 예시:
```javascript
const {app, globalShortcut} = require('electron')
app.on('ready', () => {
// '커맨드 또는 컨트롤+Y' 단축키 리스너 등록.
globalShortcut.register('CommandOrControl+Y', () => {
// 커맨드/컨트롤과 Y 가 눌렸을 때 할 동작.
})
})
```
## 플랫폼에 관련하여 주의할 점
Linux와 Windows에서는 `Command`키가 없으므로 작동하지 않습니다. 대신에

View file

@ -194,6 +194,7 @@ Returns:
* `validExpiry` Integer - 초 단위의 인증서가 만료되는 날짜
* `fingerprint` String - 인증서의 지문
* `callback` Function
* `isTrusted` Boolean - 인증서를 신뢰할지 여부
`url`에 대한 `certificate` 인증서의 유효성 검증에 실패했을 때 발생하는 이벤트입니다.
인증서를 신뢰한다면 `event.preventDefault()``callback(true)`를 호출하여
@ -222,6 +223,7 @@ Returns:
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md)
클라이언트 인증이 요청되었을 때 발생하는 이벤트입니다.
@ -256,6 +258,8 @@ Returns:
* `port` Integer
* `realm` String
* `callback` Function
* `username` String
* `password` String
`webContents`가 기본 인증을 요청할 때 발생하는 이벤트입니다.
@ -542,6 +546,7 @@ Returns `Boolean` - 호출 성공 여부.
### `app.getJumpListSettings()` _Windows_
Returns `Object`:
* `minItems` Integer - 점프 목록에서 보여질 항목의 최소 수 (이 값에 대한 자세한
설명은 [MSDN 문서][JumpListBeginListMSDN])를 보세요.
* `removedItems` [JumpListItem[]](structures/jump-list-item.md) - 점프 목록의 사용자 정의 카테고리에서 사용자가 삭제한
@ -682,6 +687,8 @@ app.setJumpList([
### `app.makeSingleInstance(callback)`
* `callback` Function
* `argv` String[] - 두번째 인스턴스의 명령줄 인수의 배열
* `workingDirectory` String - 두번째 인스턴스의 작업 디렉토리
현재 애플리케이션을 단일 인스턴스 애플리케이션으로 만들어줍니다. 이 메서드는
애플리케이션이 여러 번 실행됐을 때 다중 인스턴스가 생성되는 대신 한 개의 주
@ -814,8 +821,7 @@ Returns `Object`:
열려있었는지 여부. 이는 앱이 마지막으로 종료되었던 때에 열려있었던 윈도우를
복원하는 것을 표시합니다. 이 설정은 macOS에서만 지원됩니다.
**참고:** 이 API 는 [MAS 빌드](docs/tutorial/mac-app-store-submission-guide.md)
에 영향을 주지 않습니다.
**참고:** 이 API 는 [MAS 빌드][mas-builds]에 영향을 주지 않습니다.
### `app.setLoginItemSettings(settings)` _macOS_ _Windows_
@ -830,8 +836,7 @@ Returns `Object`:
앱의 로그인 항목 설정을 지정합니다.
**참고:** 이 API 는 [MAS 빌드](docs/tutorial/mac-app-store-submission-guide.md)
에 영향을 주지 않습니다.
**참고:** 이 API 는 [MAS 빌드][mas-builds]에 영향을 주지 않습니다.
### `app.isAccessibilitySupportEnabled()` _macOS_ _Windows_
@ -939,5 +944,6 @@ dock 아이콘의 `image`를 설정합니다.
[handoff]: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/HandoffFundamentals/HandoffFundamentals.html
[activity-type]: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUserActivity_Class/index.html#//apple_ref/occ/instp/NSUserActivity/activityType
[unity-requiremnt]: ../tutorial/desktop-environment-integration.md#unity-launcher-shortcuts-linux
[mas-builds]: docs/tutorial/mac-app-store-submission-guide.md
[JumpListBeginListMSDN]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378398(v=vs.85).aspx
[about-panel-options]: https://developer.apple.com/reference/appkit/nsapplication/1428479-orderfrontstandardaboutpanelwith?language=objc

View file

@ -118,50 +118,50 @@ child.once('ready-to-show', () => {
* `width` Integer - 윈도우의 가로 너비. 기본값은 `800`입니다.
* `height` Integer - 윈도우의 세로 높이. 기본값은 `600`입니다.
* `x` Integer (**required** y가 사용되면) - 화면을 기준으로 창 좌측을 오프셋 한 위치.
기본값은 `화면중앙`입니다.
* `y` Integer (**required** x가 사용되면) - 화면을 기준으로 창 상단을 오프셋 한 위치.
기본값은 `화면중앙`입니다.
* `x` Integer (**required** y가 사용되면) - 화면을 기준으로 창 좌측을 오프셋 한
위치. 기본값은 `화면중앙`입니다.
* `y` Integer (**required** x가 사용되면) - 화면을 기준으로 창 상단을 오프셋 한
위치. 기본값은 `화면중앙`입니다.
* `useContentSize` Boolean - `width``height`를 웹 페이지의 크기로 사용합니다.
이 속성을 사용하면 웹 페이지의 크기에 윈도우 프레임 크기가 추가되므로 실제 창은 조금
더 커질 수 있습니다. 기본값은 `false`입니다.
이 속성을 사용하면 웹 페이지의 크기에 윈도우 프레임 크기가 추가되므로 실제
창은 조금 더 커질 수 있습니다. 기본값은 `false`입니다.
* `center` Boolean - 윈도우를 화면 정 중앙에 위치시킵니다.
* `minWidth` Integer - 윈도우의 최소 가로 너비. 기본값은 `0`입니다.
* `minHeight` Integer - 윈도우의 최소 세로 높이. 기본값은 `0`입니다.
* `maxWidth` Integer - 윈도우의 최대 가로 너비. 기본값은 `제한없음`입니다.
* `maxHeight` Integer - 윈도우의 최대 세로 높이. 기본값은 `제한없음`입니다.
* `resizable` Boolean - 윈도우의 크기를 재조정 할 수 있는지 여부. 기본값은 `true`
입니다.
* `resizable` Boolean - 윈도우의 크기를 재조정 할 수 있는지 여부. 기본값은
`true` 입니다.
* `movable` Boolean - 윈도우를 이동시킬 수 있는지 여부. Linux에선 구현되어있지
않습니다. 기본값은 `true` 입니다.
* `minimizable` Boolean - 윈도우를 최소화시킬 수 있는지 여부. Linux에선 구현되어있지
* `minimizable` Boolean - 윈도우를 최소화시킬 수 있는지 여부. Linux에선
구현되어있지 않습니다. 기본값은 `true` 입니다.
* `maximizable` Boolean - 윈도우를 최대화시킬 수 있는지 여부. Linux에선
구현되어있지 않습니다. 기본값은 `true` 입니다.
* `closable` Boolean - 윈도우를 닫을 수 있는지 여부. Linux에선 구현되어있지
않습니다. 기본값은 `true` 입니다.
* `maximizable` Boolean - 윈도우를 최대화시킬 수 있는지 여부. Linux에선 구현되어있지
않습니다. 기본값은 `true` 입니다.
* `closable` Boolean - 윈도우를 닫을 수 있는지 여부. Linux에선 구현되어있지 않습니다.
기본값은 `true` 입니다.
* `focusable` Boolean - 윈도우가 포커스될 수 있는지 여부입니다. 기본값은
`true`입니다. Windows에선 `focusable: false`를 설정함으로써 암시적으로
`skipTaskbar: true`도 설정됩니다. Linux에선 `focusable: false`를 설정함으로써
윈도우가 wm과 함께 반응을 중지하며 모든 작업 영역에서 윈도우가 언제나 최상단에 있게
됩니다.
윈도우가 wm과 함께 반응을 중지하며 모든 작업 영역에서 윈도우가 언제나 최상단에
있게 됩니다.
* `alwaysOnTop` Boolean - 윈도우이 언제나 다른 창들 위에 유지되는지 여부.
기본값은 `false`입니다.
* `fullscreen` Boolean - 윈도우의 전체화면 활성화 여부. 이 속성을 명시적으로
`false`로 지정했을 경우, macOS에선 전체화면 버튼이 숨겨지거나 비활성됩니다. 기본값은
`false` 입니다.
* `fullscreenable` Boolean - 윈도우가 전체화면 모드로 전환될 수 있는지 여부입니다.
또한 macOS에선, 최대화/줌 버튼이 전체화면 모드 또는 윈도우 최대화를 실행할지 여부도
포함됩니다. 기본값은 `true`입니다.
* `skipTaskbar` Boolean - 작업표시줄 애플리케이션 아이콘 표시 스킵 여부. 기본값은
`false`입니다.
`false`로 지정했을 경우, macOS에선 전체화면 버튼이 숨겨지거나 비활성됩니다.
기본값은 `false` 입니다.
* `fullscreenable` Boolean - 윈도우가 전체화면 모드로 전환될 수 있는지
여부입니다. 또한 macOS에선, 최대화/줌 버튼이 전체화면 모드 또는 윈도우
최대화를 실행할지 여부도 포함됩니다. 기본값은 `true`입니다.
* `skipTaskbar` Boolean - 작업표시줄 애플리케이션 아이콘 표시 스킵 여부.
기본값은 `false`입니다.
* `kiosk` Boolean - Kiosk(키오스크) 모드. 기본값은 `false`입니다.
* `title` String - 기본 윈도우 제목. 기본값은 `"Electron"`입니다.
* `icon` [NativeImage](native-image.md) - 윈도우 아이콘, 생략하면 실행 파일의
아이콘이 대신 사용됩니다.
* `icon` [NativeImage](native-image.md) - 윈도우 아이콘. Windows에선 가장 좋은
시각적 효과를 얻기 위해 `ICO`를 사용하는 것을 권장하며, 또한 undefined로 남겨두면
실행 파일의 아이콘이 대신 사용됩니다.
시각적 효과를 얻기 위해 `ICO`를 사용하는 것을 권장하며, 또한 undefined로
남겨두면 실행 파일의 아이콘이 대신 사용됩니다.
On Windows it is
recommended to use `ICO` icons to get best visual effects, you can also
leave it undefined so the executable's icon will be used.
@ -169,14 +169,15 @@ On Windows it is
* `frame` Boolean - `false`로 지정하면 창을 [Frameless Window](frameless-window.md)
형태로 생성합니다. 기본값은 `true`입니다.
* `parent` BrowserWindow - 부모 윈도우를 설정합니다. 기본 값은 `null`입니다.
* `modal` Boolean - 이 윈도우가 모달 윈도우인지 여부를 설정합니다. 이 옵션은 자식
윈도우에서만 작동합니다. 기본값은 `false`입니다.
* `modal` Boolean - 이 윈도우가 모달 윈도우인지 여부를 설정합니다. 이 옵션은
자식 윈도우에서만 작동합니다. 기본값은 `false`입니다.
* `acceptFirstMouse` Boolean - 윈도우가 비활성화 상태일 때 내부 콘텐츠 클릭 시
활성화 되는 동시에 단일 mouse-down 이벤트를 발생시킬지 여부. 기본값은 `false`입니다.
* `disableAutoHideCursor` Boolean - 타이핑중 자동으로 커서를 숨길지 여부. 기본값은
`false`입니다.
* `autoHideMenuBar` Boolean - `Alt`를 누르지 않는 한 애플리케이션 메뉴바를 숨길지
여부. 기본값은 `false`입니다.
활성화 되는 동시에 단일 mouse-down 이벤트를 발생시킬지 여부. 기본값은 `false`
입니다.
* `disableAutoHideCursor` Boolean - 타이핑중 자동으로 커서를 숨길지 여부.
기본값은 `false`입니다.
* `autoHideMenuBar` Boolean - `Alt`를 누르지 않는 한 애플리케이션 메뉴바를
숨길지 여부. 기본값은 `false`입니다.
* `enableLargerThanScreen` Boolean - 윈도우 크기가 화면 크기보다 크게 재조정 될
수 있는지 여부. 기본값은 `false`입니다.
* `backgroundColor` String - `#66CD00``#FFF`, `#80FFFFFF` (알파 지원됨) 같이
@ -189,19 +190,91 @@ On Windows it is
`false`입니다.
* `type` String - 특정 플랫폼에만 적용되는 윈도우의 종류를 지정합니다. 기본값은
일반 윈도우 입니다. 사용할 수 있는 창의 종류는 아래를 참고하세요.
* `standardWindow` Boolean - macOS의 표준 윈도우를 텍스쳐 윈도우 대신 사용합니다.
기본 값은 `true`입니다.
* `titleBarStyle` String, macOS - 윈도우 타이틀 바 스타일을 지정합니다. 자세한 사항은
아래를 참고하세요.
* `thickFrame` Boolean - Windows에서 테두리 없는 윈도우를 위해 표준 윈도우 프레임을
추가하는 `WS_THICKFRAME` 스타일을 사용합니다. `false`로 지정하면 윈도우의 그림자와
애니메이션을 삭제합니다. 기본값은 `true`입니다.
* `webPreferences` Object - 웹 페이지 기능을 설정합니다. 사용할 수 있는 속성은
아래를 참고하세요.
* `standardWindow` Boolean - macOS의 표준 윈도우를 텍스쳐 윈도우 대신
사용합니다. 기본 값은 `true`입니다.
* `titleBarStyle` String, macOS - 윈도우 타이틀 바 스타일을 지정합니다. 기본값은
`default` 입니다. 가능한 값은 다음과 같습니다:
* `default` - 표준 Mac 회색 불투명 스타일을 사용합니다.
* `hidden` - 타이틀 바를 숨기고 콘텐츠 전체를 윈도우 크기에 맞춥니다.
타이틀 바는 없어지지만 표준 창 컨트롤 ("신호등 버튼")은 왼쪽 상단에
유지됩니다.
* `hidden-inset` - `hidden` 타이틀 바 속성과 함께 신호등 버튼이 윈도우
모서리로부터 약간 더 안쪽으로 들어가도록합니다. 10.9 Mavericks에선 지원되지
않고 `hidden`으로 폴백합니다.
* `thickFrame` Boolean - Windows에서 테두리 없는 윈도우를 위해 표준 윈도우
프레임을 추가하는 `WS_THICKFRAME` 스타일을 사용합니다. `false`로 지정하면
윈도우의 그림자와 애니메이션을 삭제합니다. 기본값은 `true`입니다.
* `webPreferences` Object - 웹 페이지 기능을 설정합니다.
* `nodeIntegration` Boolean - node(node.js) 통합 여부. 기본값은 `true`입니다.
* `preload` String - 스크립트를 지정하면 페이지 내의 다른 스크립트가 작동하기
전에 로드됩니다. 여기서 지정한 스크립트는 node 통합 활성화 여부에 상관없이
언제나 모든 node API에 접근할 수 있습니다. 이 속성의 스크립트 경로는 절대
경로로 지정해야 합니다. node 통합이 비활성화되어있을 경우, 미리 로드되는
스크립트는 node의 전역 심볼들을 다시 전역 범위로 다시 포함 시킬 수 있습니다.
[여기](process.md#event-loaded)의 예시를 참고하세요.
* `session` [Session](session.md#class-session) - 페이지에서 사용할 세션을
지정합니다. Session 객체를 직접적으로 전달하는 대신, 파티션 문자열을 받는
`partition` 옵션을 사용할 수도 있습니다. `session``partition`이 같이
제공되었을 경우 `session`이 사용됩니다. 기본값은 기본 세션입니다.
* `partition` String - 페이지에서 사용할 세션을 지정합니다. 만약 `partition`
`persist:`로 시작하면 페이지는 지속성 세션을 사용하며 다른 모든 앱 내의
페이지에서 같은 `partition`을 사용할 수 있습니다. 만약 `persist:` 접두어로
시작하지 않으면 페이지는 인-메모리 세션을 사용합니다. 여러 페이지에서 같은
`partition`을 지정하면 같은 세션을 공유할 수 있습니다. `partition`
지정하지 않으면 애플리케이션의 기본 세션이 사용됩니다.
* `zoomFactor` Number - 페이지의 기본 줌 값을 지정합니다. 예를 들어 `300%`
표현하려면 `3.0`으로 지정합니다. 기본값은 `1.0`입니다.
* `javascript` Boolean - 자바스크립트를 활성화합니다. 기본값은 `false`입니다.
* `webSecurity` Boolean - `false`로 지정하면 same-origin 정책을 비활성화
합니다. (이 속성은 보통 사람들에 의해 웹 사이트를 테스트할 때 사용합니다)
그리고 `allowDisplayingInsecureContent``allowRunningInsecureContent`
속성을 사용자가 `true`로 지정되지 않은 경우 `true`로 지정합니다. 기본값은
`true`입니다.
* `allowDisplayingInsecureContent` Boolean - https 페이지에서 http URL에서
로드한 이미지 같은 리소스를 표시할 수 있도록 허용합니다. 기본값은 `false`
입니다.
* `allowRunningInsecureContent` Boolean - https 페이지에서 http URL에서 로드한
JavaScript와 CSS 또는 플러그인을 실행시킬 수 있도록 허용합니다. 기본값은
`false`입니다.
* `images` Boolean - 이미지 지원을 활성화합니다. 기본값은 `true`입니다.
* `textAreasAreResizable` Boolean - HTML TextArea 요소의 크기를 재조정을
허용합니다. 기본값은 `true`입니다.
* `webgl` Boolean - WebGL 지원을 활성화합니다. 기본값은 `true`입니다.
* `webaudio` Boolean - WebAudio 지원을 활성화합니다. 기본값은 `true`입니다.
* `plugins` Boolean - 플러그인 활성화 여부를 지정합니다. 기본값은 `false`입니다.
* `experimentalFeatures` Boolean - Chrome의 실험적인 기능을 활성화합니다.
기본값은 `false`입니다.
* `experimentalCanvasFeatures` Boolean - Chrome의 실험적인 캔버스(canvas)
기능을 활성화합니다. 기본값은 `false`입니다.
* `directWrite` Boolean - Windows에서 폰트 렌더링을 위해 DirectWrite를
사용하는지를 지정합니다. 기본값은 `true`입니다.
* `scrollBounce` Boolean - macOS에서 스크롤 튕기기 효과 (탄성 밴딩)를 활성화
합니다. 기본값은 `false`입니다.
* `blinkFeatures` String - 활성화 할 `CSSVariables,KeyboardEventKey`같이 `,`
구분된 기능 문자열들의 리스트입니다. [RuntimeEnabledFeatures.in][blink-feature-string]
파일에서 찾을 수 있습니다.
* `disableBlinkFeatures` String - 비활성화 할 `CSSVariables,KeyboardEventKey`같이
`,`로 구분된 기능 문자열들의 리스트입니다. [RuntimeEnabledFeatures.in][blink-feature-string]
파일에서 찾을 수 있습니다.
* `defaultFontFamily` Object - font-family의 기본 폰트를 지정합니다.
* `standard` String - 기본값 `Times New Roman`.
* `serif` String - 기본값 `Times New Roman`.
* `sansSerif` String - 기본값 `Arial`.
* `monospace` String - 기본값 `Courier New`.
* `defaultFontSize` Integer - 기본값 `16`.
* `defaultMonospaceFontSize` Integer - 기본값 `13`.
* `minimumFontSize` Integer - 기본값 `0`.
* `defaultEncoding` String - 기본값 `ISO-8859-1`.
* `backgroundThrottling` Boolean - 페이지가 백그라운드 상태에 진입할 때
애니메이션과 타이머에 스로틀을 적용할지 여부입니다. 기본값은 `true`입니다.
* `offscreen` Boolean - 브라우저 윈도우에 오프 스크린 랜더링을 적용할지 여부를
지정합니다. 기본값은 `false`입니다.
* `sandbox` Boolean - Chromium 운영체제 수준의 샌드박스 활성화 여부.
`minWidth`/`maxWidth`/`minHeight`/`maxHeight`를 통해 최소 또는 최대 윈도우 크기를
지정한 경우, 이는 사용자만을 제약하며, `setBounds`/`setSize` 또는 `BrowserWindow`
생성자에서 크기 제약을 따르지 않는 윈도우 크기를 전달하는 것은 막을 수 없습니다.
`minWidth`/`maxWidth`/`minHeight`/`maxHeight`를 통해 최소 또는 최대 윈도우
크기를 지정한 경우, 이는 사용자만을 제약하며, `setBounds`/`setSize` 또는
`BrowserWindow`의 생성자에서 크기 제약을 따르지 않는 윈도우 크기를 전달하는 것은
막을 수 없습니다.
`type` 속성에서 사용할 수 있는 값과 동작은 다음과 같으며, 플랫폼에 따라 다릅니다:
@ -211,86 +284,11 @@ On Windows it is
* `textured`는 창에 메탈 그라디언트 외관(`NSTexturedBackgroundWindowMask`)을
설정합니다.
* `desktop`은 데스크탑 배경 레벨(`kCGDesktopWindowLevel - 1`)에 윈도우를
배치합니다. 참고로 이렇게 만들어진 윈도우는 포커스, 키보드, 마우스 이벤트를 받을
수 없습니다. 하지만 편법으로 `globalShortcut`을 통해 키 입력을 받을 수 있습니다.
배치합니다. 참고로 이렇게 만들어진 윈도우는 포커스, 키보드, 마우스 이벤트를
받을 수 없습니다. 하지만 편법으로 `globalShortcut`을 통해 키 입력을 받을 수
있습니다.
* Windows의 경우, 가능한 타입으론 `toolbar`가 있습니다.
`titleBarStyle`의 속성은 다음과 같습니다:
* `default` 또는 미지정: 표준 Mac 회색 불투명 스타일을 사용합니다.
* `hidden`: 타이틀 바를 숨기고 콘텐츠 전체를 윈도우 크기에 맞춥니다.
타이틀 바는 없어지지만 표준 창 컨트롤 ("신호등 버튼")은 왼쪽 상단에 유지됩니다.
* `hidden-inset`: `hidden` 타이틀 바 속성과 함께 신호등 버튼이 윈도우 모서리로부터
약간 더 안쪽으로 들어가도록합니다. 10.9 Mavericks에선 지원되지 않고 `hidden`으로
폴백합니다.
`webPreferences` 속성은 다음과 같은 속성을 가질 수 있습니다:
* `nodeIntegration` Boolean - node(node.js) 통합 여부. 기본값은 `true`입니다.
* `preload` String - 스크립트를 지정하면 페이지 내의 다른 스크립트가 작동하기 전에
로드됩니다. 여기서 지정한 스크립트는 node 통합 활성화 여부에 상관없이 언제나 모든
node API에 접근할 수 있습니다. 이 속성의 스크립트 경로는 절대 경로로 지정해야
합니다. node 통합이 비활성화되어있을 경우, preload 스크립트는 node의 global
심볼들을 다시 global 스코프로 다시 포함 시킬 수 있습니다.
[여기](process.md#event-loaded)의 예시를 참고하세요.
* `session` [Session](session.md#class-session) - 페이지에서 사용할 세션을
지정합니다. Session 객체를 직접적으로 전달하는 대신, 파티션 문자열을 받는
`partition` 옵션을 사용할 수도 있습니다. `session``partition`이 같이
제공되었을 경우 `session`이 사용됩니다. 기본값은 기본 세션입니다.
* `partition` String - 페이지에서 사용할 세션을 지정합니다. 만약 `partition`
`persist:`로 시작하면 페이지는 지속성 세션을 사용하며 다른 모든 앱 내의
페이지에서 같은 `partition`을 사용할 수 있습니다. 만약 `persist:` 접두어로
시작하지 않으면 페이지는 인-메모리 세션을 사용합니다. 여러 페이지에서 같은
`partition`을 지정하면 같은 세션을 공유할 수 있습니다. `partition`을 지정하지
않으면 애플리케이션의 기본 세션이 사용됩니다.
* `zoomFactor` Number - 페이지의 기본 줌 값을 지정합니다. 예를 들어 `300%`
표현하려면 `3.0`으로 지정합니다. 기본값은 `1.0`입니다.
* `javascript` Boolean - 자바스크립트를 활성화합니다. 기본값은 `false`입니다.
* `webSecurity` Boolean - `false`로 지정하면 same-origin 정책을 비활성화합니다.
(이 속성은 보통 사람들에 의해 웹 사이트를 테스트할 때 사용합니다) 그리고
`allowDisplayingInsecureContent``allowRunningInsecureContent` 두 속성을
사용자가 `true`로 지정되지 않은 경우 `true`로 지정합니다. 기본값은
`true`입니다.
* `allowDisplayingInsecureContent` Boolean - https 페이지에서 http URL에서
로드한 이미지 같은 리소스를 표시할 수 있도록 허용합니다. 기본값은 `false`입니다.
* `allowRunningInsecureContent` Boolean - https 페이지에서 http URL에서 로드한
JavaScript와 CSS 또는 플러그인을 실행시킬 수 있도록 허용합니다. 기본값은
`false`입니다.
* `images` Boolean - 이미지 지원을 활성화합니다. 기본값은 `true`입니다.
* `textAreasAreResizable` Boolean - HTML TextArea 요소의 크기를 재조정을
허용합니다. 기본값은 `true`입니다.
* `webgl` Boolean - WebGL 지원을 활성화합니다. 기본값은 `true`입니다.
* `webaudio` Boolean - WebAudio 지원을 활성화합니다. 기본값은 `true`입니다.
* `plugins` Boolean - 플러그인 활성화 여부를 지정합니다. 기본값은 `false`입니다.
* `experimentalFeatures` Boolean - Chrome의 실험적인 기능을 활성화합니다.
기본값은 `false`입니다.
* `experimentalCanvasFeatures` Boolean - Chrome의 실험적인 캔버스(canvas) 기능을
활성화합니다. 기본값은 `false`입니다.
* `directWrite` Boolean - Windows에서 폰트 렌더링을 위해 DirectWrite를
사용하는지를 지정합니다. 기본값은 `true`입니다.
* `scrollBounce` Boolean - macOS에서 스크롤 튕기기 효과 (탄성 밴딩)를 활성화 합니다.
기본값은 `false`입니다.
* `blinkFeatures` String - 활성화 할 `CSSVariables,KeyboardEventKey`같이 `,`
구분된 기능 문자열들의 리스트입니다. [RuntimeEnabledFeatures.in][blink-feature-string]
파일에서 찾을 수 있습니다.
* `disableBlinkFeatures` String - 비활성화 할 `CSSVariables,KeyboardEventKey`같이
`,`로 구분된 기능 문자열들의 리스트입니다. [RuntimeEnabledFeatures.in][blink-feature-string]
파일에서 찾을 수 있습니다.
* `defaultFontFamily` Object - font-family의 기본 폰트를 지정합니다.
* `standard` String - 기본값 `Times New Roman`.
* `serif` String - 기본값 `Times New Roman`.
* `sansSerif` String - 기본값 `Arial`.
* `monospace` String - 기본값 `Courier New`.
* `defaultFontSize` Integer - 기본값 `16`.
* `defaultMonospaceFontSize` Integer - 기본값 `13`.
* `minimumFontSize` Integer - 기본값 `0`.
* `defaultEncoding` String - 기본값 `ISO-8859-1`.
* `backgroundThrottling` Boolean - 페이지가 백그라운드 상태에 진입할 때 애니메이션과
타이머에 스로틀을 적용할지 여부입니다. 기본값은 `true`입니다.
* `offscreen` Boolean - 브라우저 윈도우에 오프 스크린 랜더링을 적용할지 여부를
지정합니다. 기본값은 `false`입니다.
* `sandbox` Boolean - Chromium 운영체제 수준의 샌드박스 활성화 여부.
### Instance Events
`new BrowserWindow`로 생성된 객체는 다음과 같은 이벤트를 발생시킵니다:
@ -654,6 +652,17 @@ Returns `Boolean` - 윈도우가 전체화면 모드인지 여부.
크기는 관여하지 않습니다. 그저 전체 콘텐츠 뷰 내에 있는 모든 엑스트라 너비, 높이 영역이
합해집니다.
#### `win.previewFile(path[, displayName])` _macOS_
* `path` String - QuickLook 으로 미리 볼 파일에 대한 절대 경로. Quick Look 이
열기 위한 파일의 컨텐츠 형식을 결정하는데 경로의 파일명과 확장자를 사용하기
때문에 중요합니다.
* `displayName` String (Optional) - Quick Look 모달 뷰에 표시되는 파일의 이름.
이것은 순전히 보여주는 용도이며 파일의 컨텐츠 형식에 영향을 주지 않습니다.
기본값은 `path` 입니다.
주어진 경로의 파일을 미리 보여주기 위해 [Quick Look][quick-look] 을 사용하세요.
#### `win.setBounds(bounds[, animate])`
* `bounds` [Rectangle](structures/rectangle.md)
@ -941,6 +950,7 @@ Returns `Boolean` - 윈도우의 문서가 변경되었는지 여부.
* `rect` [Rectangle](structures/rectangle.md) (optional) - 캡쳐될 페이지의 영역
* `callback` Function
* `image` [NativeImage](native-image.md)
`webContents.capturePage([rect, ]callback)`와 같습니다.
@ -1098,7 +1108,7 @@ Returns `Boolean` - 버튼이 성공적으로 추가되었는지 여부
Returns `Boolean` - 메뉴 막대 자동 숨김 상태 여부.
#### `win.setMenuBarVisibility(visible)`
#### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` Boolean
@ -1167,3 +1177,4 @@ Returns `BrowserWindow[]` - 모든 자식 윈도우.
[blink-feature-string]: https://cs.chromium.org/chromium/src/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.in
[window-levels]: https://developer.apple.com/reference/appkit/nswindow/1664726-window_levels
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look

View file

@ -80,6 +80,7 @@ Returns `String` - RTF 형식의 클립보드 내용.
### `clipboard.readBookmark()` _macOS_ _Windows_
Returns `Object`:
* `title` String
* `url` String
@ -104,6 +105,19 @@ clipboard.write({
})
```
### `clipboard.readFindText()` _macOS_
Returns `String` - FindPasteboard 의 텍스트. 이 메소드는 렌더러 프로세스에서
호출되었을 떄 동기 IPC 를 사용합니다. 캐시된 값은 애플리케이션이 활성화될 때
마다 FindPasteboard 에서 다시 읽습니다.
### `clipboard.writeFindText(text)` _macOS_
* `text` String
`text` 를 FindPasteboard 에 일반 텍스트로 씁니다. 이 메소드는 렌더러
프로세스에서 호출되었을 떄 동기 IPC 를 사용합니다.
### `clipboard.clear([type])`
* `type` String (optional)

View file

@ -31,7 +31,8 @@ contentTracing.startRecording(options, () => {
### `contentTracing.getCategories(callback)`
* `callback` Function
* `callback`
* `categories` String[]
카테고리 그룹 세트를 가져옵니다. 카테고리 그룹은 도달된 코드 경로를 변경할 수 있습니다.
@ -85,6 +86,7 @@ EnableRecording 요청을 받게 됩니다. 모든 child 프로세스가 `startR
* `resultFilePath` String
* `callback` Function
* `resultFilePath` String
모든 프로세스에서 레코딩을 중지합니다.
@ -127,6 +129,7 @@ Child 프로세스는 일반적으로 추적 데이터와 희귀한 플러시
* `resultFilePath` String
* `callback` Function
* `resultFilePath` String
현재 모니터링 추적 데이터를 가져옵니다.
@ -142,6 +145,8 @@ Child 프로세스는 일반적으로 추적 데이터와 희귀한 플러시
### `contentTracing.getTraceBufferUsage(callback)`
* `callback` Function
* `value` Number
* `percentage` Number
추적 버퍼 % 전체 상태의 프로세스간 최대치를 가져옵니다. TraceBufferUsage 값이
결정되면 `callback`이 한 번 호출됩니다.

View file

@ -53,6 +53,7 @@ crashReporter.start({
### `crashReporter.getLastCrashReport()`
Returns `Object`:
* `date` String
* `ID` Integer
@ -62,6 +63,7 @@ Returns `Object`:
### `crashReporter.getUploadedReports()`
Returns `Object[]`:
* `date` String
* `ID` Integer

View file

@ -62,21 +62,14 @@ function handleError (e) {
* `thumbnailSize` Object (optional) - 미디어 소스 섬네일의 크기가 맞춰져야 할
제안된 크기, 기본값은 `{width: 150, height: 150}`입니다.
* `callback` Function
* `error` Error
* `sources` [DesktopCapturerSource[]](structures/desktop-capturer-source.md)
사용할 수 있는 데스크톱 미디어 소스를 가져오기 시작하고 작업이 완료되면
`callback(error, sources)`가 호출됩니다.
`sources``Source`객체의 배열이며, 각 `Source`는 캡쳐될 수 있는 스크린과 각기
윈도우를 표현합니다. 그리고 다음과 같은 속성을 가지고 있습니다:
* `id` String - 윈도우 또는 스크린의 식별자로써 [`navigator.webkitGetUserMedia`]를
호출할 때 `chromeMediaSourceId` 속성에 사용될 수 있습니다. 식별자의 형식은
`window:XX` 또는 `screen:XX` 이며 `XX` 부분은 무작위로 생성된 숫자입니다.
* `name` String - `Entire Screen` 또는 `Screen <index>`로 이름지어질 스크린
소스이며, 이는 윈도우 제목에 일치하는 윈도우 소스의 이름이 됩니다.
* `thumbnail` [NativeImage](native-image.md) - 섬네일 이미지입니다. **참고:**
`desktopCapturer.getSources`로 전달된 `options` 객체의 `thumnbailSize` 속성과
같이 이 섬네일의 사이즈가 완전히 같을 것이라고 보장하지 않습니다. 실질적인 크기는
스크린과 윈도우의 비율에 따라 달라질 수 있습니다.
`sources` 는 [`DesktopCapturerSource`](structures/desktop-capturer-source.md)
객체의 배열이며, 각 `DesktopCapturerSource` 는 캡쳐 가능한 화면 또는 개별
윈도우입니다.
[`navigator.webkitGetUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/Navigator/getUserMedia

View file

@ -34,6 +34,7 @@ console.log(dialog)
다음을 포함할 수 있습니다: `openFile`, `openDirectory`, `multiSelections`,
`createDirectory`, `showHiddenFiles`.
* `callback` Function (optional)
* `filePaths` String[] - 사용자가 선택한 파일 경로의 배열
사용할 대화 상자의 기능이 담긴 배열입니다. 다음을 포함할 수 있습니다: `openFile`,
`openDirectory`, `multiSelections`, `createDirectory`
@ -77,6 +78,7 @@ console.log(dialog)
라벨이 사용됩니다.
* `filters` String[]
* `callback` Function (optional)
* `filename` String
작업에 성공하면 콜백으로 유저가 선택한 파일의 경로를 포함한 배열을 반환합니다. 그 외엔
`undefined`를 반환합니다.
@ -112,6 +114,7 @@ console.log(dialog)
만듭니다. 이 기능으로 앱을 좀 더 현대적인 Windows 앱처럼 만들 수 있습니다. 이
기능을 원하지 않으면 `noLink`를 true로 지정하면 됩니다.
* `callback` Function (optional)
* `response` Number - 눌려진 버튼의 인덱스
대화 상자를 표시합니다. `browserWindow`를 지정하면 대화 상자가 완전히 닫힐 때까지
지정한 창을 사용할 수 없습니다. 완료 시 유저가 선택한 버튼의 인덱스를 반환합니다.

View file

@ -24,8 +24,26 @@ macOS 10.9 Mavericks 이후의 최신 버전부터는 테두리가 없는 창을
비활성화하는 대신 새로운 `titleBarStyle` 옵션을 통해 제목만 숨기고 창 구성 요소
("신호등 버튼")의 기능과 창 크기를 그대로 유지할 수 있습니다:
#### `hidden`
제목 표시줄을 숨기고 컨텐츠 창을 전체 크기로 합니다. 제목 표시줄은 여전히 왼쪽
상단에 표준 창 컨트롤 (“신호등”) 을 가지고 있습니다.
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden'})
win.show()
```
#### `hidden-inset`
제목 표시줄을 숨기고 창 가장자리에 약간 더 들어간 신호등 버튼 모양으로
대체합니다.
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden-inset'})
win.show()
```
## 투명한 창 만들기

View file

@ -13,6 +13,9 @@
* `options` Object
* `click` Function - 메뉴 아이템이 클릭될 때 `click(menuItem, browserWindow,
event)` 형태로 호출 되는 콜백 함수.
* `menuItem` MenuItem
* `browserWindow` BrowserWindow
* `event` Event
* `role` String - 메뉴 아이템의 액션을 정의합니다. 이 속성을 지정하면 `click`
속성이 무시됩니다.
* `type` String - `MenuItem`의 타입 `normal`, `separator`, `submenu`,

View file

@ -84,6 +84,7 @@ Mac App Store 빌드에선 이 속성이 `true`가 됩니다. 다른 빌드에
### `process.getProcessMemoryInfo()`
Returns `Object`:
* `workingSetSize` Integer - 현재 실제 물리적 RAM에 예약된 메모리의 양.
* `peakWorkingSetSize` Integer - 물리적 RAM에 예약된 메모리의 최대 사용량.
* `privateBytes` Integer - 다른 프로세스에 공유되지 않은 JS 힙 또는 HTML 콘텐츠와
@ -97,6 +98,7 @@ Returns `Object`:
### `process.getSystemMemoryInfo()`
Returns `Object`:
* `total` Integer - 시스템에서 사용할 수 있는 킬로바이트 단위의 전체 물리적 메모리의
양.
* `free` Integer - 애플리케이션이나 디스크 캐시로 사용되지 않은 메모리의 양.

View file

@ -75,29 +75,21 @@ app.on('ready', () => {
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String (optional)
* `completion` Function (optional)
* `error` Error
`scheme`에 파일을 응답으로 보내는 프로토콜을 등록합니다. `handler``scheme`와 함께
`request`가 생성될 때 `handler(request, callback)` 형식으로 호출됩니다.
`completion` 콜백은 `scheme`가 성공적으로 등록되었을 때 `completion(null)` 형식으로
호출되고, 등록에 실패했을 땐 `completion(error)` 형식으로 에러 내용을 담아 호출됩니다.
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` Array (optional)
* `callback` Function
`uploadData``data` 객체의 배열입니다:
* `data` Object
* `bytes` Buffer - 전송될 콘텐츠.
* `file` String - 업로드될 파일의 경로.
* `blobUUID` String - blob 데이터의 UUID. 데이터를 이용하기 위해
[ses.getBlobData](session.md#sesgetblobdataidentifier-callback) 메소드를
사용하세요.
`request`를 처리할 때 반드시 파일 경로 또는 `path` 속성을 포함하는 객체를 인수에
포함하여 `callback`을 호출해야 합니다. 예: `callback(filePath)` 또는
`callback({path: filePath})`.
@ -114,7 +106,15 @@ app.on('ready', () => {
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `buffer` Buffer (optional)
* `completion` Function (optional)
* `error` Error
`Buffer`를 응답으로 전송하는 `scheme`의 프로토콜을 등록합니다.
@ -138,7 +138,15 @@ protocol.registerBufferProtocol('atom', (request, callback) => {
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `buffer` Buffer (optional)
* `completion` Function (optional)
* `error` Error
`String`을 응답으로 전송할 `scheme`의 프로토콜을 등록합니다.
@ -150,7 +158,21 @@ protocol.registerBufferProtocol('atom', (request, callback) => {
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
* `contentType` String - 콘텐츠의 MIME 타입.
* `data` String - 전송할 콘텐츠.
* `completion` Function (optional)
* `error` Error
HTTP 요청을 응답으로 전송할 `scheme`의 프로토콜을 등록합니다.
@ -158,25 +180,16 @@ HTTP 요청을 응답으로 전송할 `scheme`의 프로토콜을 등록합니
`session` 속성을 포함하는 `redirectRequest` 객체와 함께 호출되어야 한다는 점을
제외하면 `registerFileProtocol`과 사용법이 같습니다.
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
기본적으로 HTTP 요청은 현재 세션을 재사용합니다. 만약 서로 다른 세션에 요청을 보내고
싶으면 `session``null`로 지정해야 합니다.
POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `uploadData` object
* `contentType` String - 콘텐츠의 MIME 타입.
* `data` String - 전송할 콘텐츠.
### `protocol.unregisterProtocol(scheme[, completion])`
* `scheme` String
* `completion` Function (optional)
* `error` Error
`scheme`의 커스텀 프로토콜 등록을 해제합니다.
@ -184,6 +197,7 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `callback` Function
* `error` Error
`scheme`에 동작(handler)이 등록되어 있는지 여부를 확인합니다. `callback`으로
결과(boolean)가 반환됩니다.
@ -192,7 +206,15 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String
* `completion` Function (optional)
* `error` Error
`scheme` 프로토콜을 가로채고 `handler`를 파일 전송에 대한 새로운 동작으로 사용합니다.
@ -200,7 +222,15 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String
* `completion` Function (optional)
* `error` Error
`scheme` 프로토콜을 가로채고 `handler`를 문자열 전송에 대한 새로운 동작으로 사용합니다.
@ -208,7 +238,15 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String
* `completion` Function (optional)
* `error` Error
`scheme` 프로토콜을 가로채고 `handler``Buffer` 전송에 대한 새로운 동작으로
사용합니다.
@ -217,7 +255,21 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
* `contentType` String - 콘텐츠의 MIME 타입.
* `data` String - 전송할 콘텐츠.
* `completion` Function (optional)
* `error` Error
`scheme` 프로토콜을 가로채고 `handler`를 HTTP 프로토콜의 요청에 대한 새로운 동작으로
사용합니다.
@ -226,6 +278,7 @@ POST 요청에는 반드시 `uploadData` 객체가 제공되어야 합니다.
* `scheme` String
* `completion` Function (optional)
* `error` Error
가로챈 `scheme`를 삭제하고 기본 핸들러로 복구합니다.

View file

@ -90,6 +90,7 @@ Returns:
### `screen.getCursorScreenPoint()`
Returns `Object`:
* `x` Integer
* `y` Integer

View file

@ -201,6 +201,7 @@ proxyURL = [<proxyScheme>"://"]<proxyHost>[":"<proxyPort>]
* `url` URL
* `callback` Function
* `proxy` Object
`url`의 프록시 정보를 해석합니다. `callback`은 요청이 수행되었을 때
`callback(proxy)` 형태로 호출됩니다.
@ -244,7 +245,11 @@ window.webContents.session.enableNetworkEmulation({offline: true})
#### `ses.setCertificateVerifyProc(proc)`
* `proc` Function
* `proc` Function
* `hostname` String
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` Boolean - 인증서를 신뢰해야하는지 결정
`session`에 인증서의 유효성을 확인하는 프로세스(proc)를 등록합니다. `proc`은 서버
인증서 유효성 검증 요청이 들어왔을 때 언제나 `proc(hostname, certificate, callback)`
@ -267,7 +272,8 @@ win.webContents.session.setCertificateVerifyProc((hostname, cert, callback) => {
* `webContents` Object - [WebContents](web-contents.md) 권한을 요청.
* `permission` String - 'media', 'geolocation', 'notifications',
'midiSysex', 'pointerLock', 'fullscreen', 'openExternal'의 나열.
* `callback` Function - 권한 허용 및 거부.
* `callback` Function
* `permissionGranted` Boolean - 권한 허용 및 거부.
`session`의 권한 요청에 응답을 하는데 사용하는 핸들러를 설정합니다.
`callback(true)`를 호출하면 권한 제공을 허용하고 `callback(false)`
@ -396,7 +402,7 @@ session.defaultSession.cookies.set(cookie, (error) => {
#### Event: 'changed'
* `event` Event
* `cookie` Object - 변경된 쿠키
* `cookie` [Cookie](structures/cookie.md) - 변경된 쿠키
* `cause` String - 다음 값 중 하나인 변경된 이유:
* `explicit` - 쿠키가 소비자의 행위에 의해 직접 변경되었습니다.
* `overwrite` - 쿠키를 덮어쓰는 삽입 동작에 의해 자동으로 제거되었습니다.
@ -423,24 +429,13 @@ session.defaultSession.cookies.set(cookie, (error) => {
* `secure` Boolean (optional) - 보안 속성에 따라 쿠키를 필터링합니다.
* `session` Boolean (optional) - 세션 또는 지속성 쿠키를 필터링합니다.
* `callback` Function
* `error` Error
* `cookies` Cookies[]
`details` 객체에서 묘사한 모든 쿠키를 요청합니다. 모든 작업이 끝나면 `callback`
`callback(error, cookies)` 형태로 호출됩니다.
`cookies``cookie` 객체의 배열입니다.
* `cookie` Object
* `name` String - 쿠키의 이름.
* `value` String - 쿠키의 값.
* `domain` String - 쿠키의 도메인.
* `hostOnly` String - 쿠키가 호스트 전용인가에 대한 여부.
* `path` String - 쿠키의 경로.
* `secure` Boolean - 쿠키가 안전한 것으로 표시되는지에 대한 여부.
* `httpOnly` Boolean - 쿠키가 HTTP로만 표시되는지에 대한 여부.
* `session` Boolean - 쿠키가 세션 쿠키 또는 만료일이 있는 영구 쿠키인지에 대한
여부.
* `expirationDate` Double - (Option) UNIX 시간으로 표시되는 쿠키의 만료일에
대한 초 단위 시간. 세션 쿠키는 지원되지 않음.
`cookies`는 [`cookie`](structures/cookie.md) 객체의 배열입니다.
#### `ses.cookies.set(details, callback)`
@ -458,6 +453,7 @@ session.defaultSession.cookies.set(cookie, (error) => {
대한 초 단위 시간입니다. 생략되면 쿠키가 세션 쿠기가 되며 세션 사이에 유지되지
않게 됩니다.
* `callback` Function
* `error` Error
`details` 객체에 따라 쿠키를 설정합니다. 작업이 완료되면 `callback`
`callback(error)` 형태로 호출됩니다.
@ -521,24 +517,16 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback
* `method` String
* `resourceType` String
* `timestamp` Double
* `uploadData` Array (optional)
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `response` Object
* `cancel` Boolean (optional)
* `redirectURL` String (optional) - 원래 요청이 전송되거나 완료되는 것을
방지하고 지정된 URL 로 리디렉션됩니다.
`uploadData``data` 객체의 배열입니다:
`uploadData``uploadData` 객체의 배열입니다.
* `data` Object
* `bytes` Buffer - 전송될 콘텐츠.
* `file` String - 업로드될 파일의 경로.
* `blobUUID` String - blob 데이터의 UUID. 데이터를 이용하기 위해
[ses.getBlobData](session.md#sesgetblobdataidentifier-callback) 메소드를
사용하세요.
`callback``response` 객체와 함께 호출되어야 합니다:
* `response` Object
* `cancel` Boolean (optional)
* `redirectURL` String (optional) - 원래 요청은 전송과 완료가 방지되지만 이
속성을 지정하면 해당 URL로 리다이렉트됩니다.
`callback``response` 객체와 함께 호출되어야 합니다.
#### `webRequest.onBeforeSendHeaders([filter, ]listener)`
@ -557,31 +545,29 @@ HTTP 요청을 보내기 전 요청 헤더를 사용할 수 있을 때 `listener
* `timestamp` Double
* `requestHeaders` Object
* `callback` Function
* `response` Object
* `cancel` Boolean (optional)
* `requestHeaders` Object (optional) - 이 속성이 제공되면, 요청은 이 헤더로
만들어 집니다.
`callback``response` 객체와 함께 호출되어야 합니다:
* `response` Object
* `cancel` Boolean (optional)
* `requestHeaders` Object (optional) - 이 속성이 제공되면, 요청은 이 헤더로
만들어 집니다.
`callback``response` 객체와 함께 호출되어야 합니다.
#### `webRequest.onSendHeaders([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `requestHeaders` Object
서버에 요청이 전송되기 바로 전에 `listener``listener(details)` 형태로 호출됩니다.
이전 `onBeforeSendHeaders`의 response와 다른점은 리스너가 호출되는 시간으로 볼 수
있습니다.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `requestHeaders` Object
#### `webRequest.onHeadersReceived([filter, ]listener)`
* `filter` Object
@ -600,86 +586,81 @@ HTTP 요청을 보내기 전 요청 헤더를 사용할 수 있을 때 `listener
* `statusCode` Integer
* `responseHeaders` Object
* `callback` Function
* `response` Object
* `cancel` Boolean
* `responseHeaders` Object (optional) - 이 속성이 제공되면 서버는 이 헤더와
함께 응답합니다.
* `statusLine` String (optional) - `responseHeaders`를 덮어쓸 땐, 헤더의
상태를 변경하기 위해 반드시 지정되어야 합니다. 그렇지 않은 경우, 기존의
응답 헤더의 상태가 사용됩니다.
`callback``response` 객체와 함께 호출되어야 합니다:
* `response` Object
* `cancel` Boolean
* `responseHeaders` Object (optional) - 이 속성이 제공되면 서버는 이 헤더와
함께 응답합니다.
* `statusLine` String (optional) - `responseHeaders`를 덮어쓸 땐, 헤더의 상태를
변경하기 위해 반드시 지정되어야 합니다. 그렇지 않은 경우, 기존의 응답 헤더의 상태가
사용됩니다.
`callback``response` 객체와 함께 호출되어야 합니다.
#### `webRequest.onResponseStarted([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean - 응답을 디스크 캐시에서 가져올지에 대한 여부.
* `statusCode` Integer
* `statusLine` String
요청 본문의 첫 번째 바이트를 받았을 때 `listener``listener(details)` 형태로
호출됩니다. 이는 HTTP 요청에서 상태 줄과 요청 헤더가 사용 가능한 상태를 의미합니다.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean - 응답을 디스크 캐시에서 가져올지에 대한 여부.
* `statusCode` Integer
* `statusLine` String
#### `webRequest.onBeforeRedirect([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` String
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `redirectURL` String
* `statusCode` Integer
* `ip` String (optional) - 요청이 실질적으로 전송될 서버 아이피 주소.
* `fromCache` Boolean
* `responseHeaders` Object
서버에서 시작된 리다이렉트가 발생했을 때 `listener``listener(details)` 형태로
호출됩니다.
* `details` Object
* `id` String
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `redirectURL` String
* `statusCode` Integer
* `ip` String (optional) - 요청이 실질적으로 전송될 서버 아이피 주소.
* `fromCache` Boolean
* `responseHeaders` Object
#### `webRequest.onCompleted([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean
* `statusCode` Integer
* `statusLine` String
요청이 완료되면 `listener``listener(details)` 형태로 호출됩니다.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean
* `statusCode` Integer
* `statusLine` String
#### `webRequest.onErrorOccurred([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `fromCache` Boolean
* `error` String - 에러 설명.
에러가 발생하면 `listener``listener(details)` 형태로 호출됩니다.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `fromCache` Boolean
* `error` String - 에러 설명.

View file

@ -0,0 +1,4 @@
# BluetoothDevice Object
* `deviceName` String
* `deviceId` String

View file

@ -0,0 +1,13 @@
# Cookie Object
* `name` String - 쿠키의 이름.
* `value` String - 쿠키의 값.
* `domain` String - 쿠키의 도메인.
* `hostOnly` String - 쿠키가 호스트 전용인가에 대한 여부.
* `path` String - 쿠키의 경로.
* `secure` Boolean - 쿠키가 안전한 것으로 표시됐는지에 대한 여부.
* `httpOnly` Boolean - 쿠키가 HTTP 전용으로 표시됐는지에 대한 여부.
* `session` Boolean - 쿠키가 세션 쿠키인지 만료일이 있는 영구 쿠키인지에 대한
여부.
* `expirationDate` Double - (Optional) UNIX 시간으로 표시되는 쿠키의 만료일에
대한 초 단위 시간. 세션 쿠키는 지원되지 않음.

View file

@ -0,0 +1,12 @@
# DesktopCapturerSource Object
* `id` String - [`navigator.webkitGetUserMedia`] 를 호출할 때
`chromeMediaSourceId` 제한으로 사용될 수 있는 윈도우 또는 화면의 식별자.
식별자의 형식은 `window:XX` 또는 `screen:XX` 이 될 것 이며, `XX` 는 무작위로
생성된 숫자입니다.
* `name` String - 윈도우 소스의 이름이 윈도우 제목과 일치하면, 화면 소스는
`Entire Screen` 또는 `Screen <index>` 으로 명명될 것 입니다.
* `thumbnail` [NativeImage](../native-image.md) - 섬네일 이미지. **참고:**
`desktopCapturer.getSources` 에 넘겨진 `options` 에 명시된 `thumbnailSize`
섬네일의 크기가 같음을 보장하지 않습니다. 실제 크기는 화면이나 윈도우의 규모에
의해 결정됩니다.

View file

@ -0,0 +1,7 @@
# UploadData Object
* `bytes` Buffer - 전송되는 내용.
* `file` String - 업로드되는 파일의 경로.
* `blobUUID` String - BLOB 데이터의 UUID. 데이터를 이용하려면
[ses.getBlobData](../session.md#sesgetblobdataidentifier-callback) 메소드를
사용하세요.

View file

@ -62,6 +62,8 @@ macOS 의 기본 알림으로 `event` 를 전달합니다. `userInfo` 는 알림
* `event` String
* `callback` Function
* `event` String
* `userInfo` Object
macOS의 기본 알림을 구독하며, 해당하는 `event`가 발생하면 `callback`
`callback(event, userInfo)` 형태로 호출됩니다. `userInfo`는 알림과 함께 전송되는
@ -87,6 +89,8 @@ macOS의 기본 알림을 구독하며, 해당하는 `event`가 발생하면 `ca
* `event` String
* `callback` Function
* `event` String
* `userInfo` Object
`subscribeNotification`와 같습니다. 하지만 로컬 기본값에 대해
`NSNotificationCenter`를 사용합니다. 이는 `NSUserDefaultsDidChangeNotification`

View file

@ -145,9 +145,10 @@ Returns:
* `frameName` String
* `disposition` String - `default`, `foreground-tab`, `background-tab`,
`new-window`, `save-to-disk`, `other`중 하나일 수 있습니다.
* `options` Object - 새로운 `BrowserWindow` 객체를 만들 때 사용되는 옵션 객체입니다.
* `additionalFeatures` Array - `window.open()` 에 주어진 (Chromium 또는 Electron
에 의해 처리되지 않는) 비표준 기능.
* `options` Object - 새로운 `BrowserWindow` 객체를 만들 때 사용되는 옵션
객체입니다.
* `additionalFeatures` String[] - `window.open()` 에 주어진 (Chromium 또는
Electron 에 의해 처리되지 않는) 비표준 기능.
페이지가 `url`에 대하여 새로운 윈도우를 열기위해 요청한 경우 발생하는 이벤트입니다.
`window.open`이나 `<a target='_blank'>`과 같은 외부 링크에 의해 요청될 수 있습니다.
@ -246,6 +247,8 @@ Returns:
* `error` String - 에러 코드
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` Boolean - 인증서가 신뢰할 수 있는 것으로 간주할 수 있는지 여부를
나타냅니다
`url`에 대한 `certificate` 인증서의 유효성 검증에 실패했을 때 발생하는 이벤트입니다.
@ -258,8 +261,10 @@ Returns:
* `event` Event
* `url` URL
* `certificateList` Certificate[]
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md) - 인증서는 주어진
목록에 있어야합니다.
클라이언트 인증이 요청되었을 때 발생하는 이벤트입니다.
@ -282,6 +287,8 @@ Returns:
* `port` Integer
* `realm` String
* `callback` Function
* `username` String
* `password` String
`webContents`가 기본 인증을 수행하길 원할 때 발생되는 이벤트입니다.
@ -384,31 +391,24 @@ Returns:
종류. 값은 `none`, `plainText`, `password`, `other` 중 한 가지가 될 수 있습니다.
* `menuSourceType` String - 컨텍스트 메뉴를 호출한 입력 소스. 값은 `none`,
`mouse`, `keyboard`, `touch`, `touchMenu` 중 한 가지가 될 수 있습니다.
* `mediaFlags` Object - 컨텍스트 메뉴가 호출된 미디어 요소에 대한 플래그. 자세한
사항은 아래를 참고하세요.
* `mediaFlags` Object - 컨텍스트 메뉴가 호출된 미디어 요소에 대한 플래그.
* `inError` Boolean - 미디어 객체가 크래시되었는지 여부.
* `isPaused` Boolean - 미디어 객체가 일시중지되었는지 여부.
* `isMuted` Boolean - 미디어 객체가 음소거되었는지 여부.
* `hasAudio` Boolean - 미디어 객체가 오디오를 가지고 있는지 여부.
* `isLooping` Boolean - 미디어 객체가 루프중인지 여부.
* `isControlsVisible` Boolean - 미디어 객체의 컨트롤이 보이는지 여부.
* `canToggleControls` Boolean - 미디어 객체의 컨트롤을 토글할 수 있는지 여부.
* `canRotate` Boolean - 미디어 객체를 돌릴 수 있는지 여부.
* `editFlags` Object - 이 플래그는 렌더러가 어떤 행동을 이행할 수 있는지 여부를
표시합니다. 자세한 사항은 아래를 참고하세요.
`mediaFlags`는 다음과 같은 속성을 가지고 있습니다:
* `inError` Boolean - 미디어 객체가 크래시되었는지 여부.
* `isPaused` Boolean - 미디어 객체가 일시중지되었는지 여부.
* `isMuted` Boolean - 미디어 객체가 음소거되었는지 여부.
* `hasAudio` Boolean - 미디어 객체가 오디오를 가지고 있는지 여부.
* `isLooping` Boolean - 미디어 객체가 루프중인지 여부.
* `isControlsVisible` Boolean - 미디어 객체의 컨트롤이 보이는지 여부.
* `canToggleControls` Boolean - 미디어 객체의 컨트롤을 토글할 수 있는지 여부.
* `canRotate` Boolean - 미디어 객체를 돌릴 수 있는지 여부.
`editFlags`는 다음과 같은 속성을 가지고 있습니다:
* `canUndo` Boolean - 렌더러에서 실행 취소할 수 있는지 여부.
* `canRedo` Boolean - 렌더러에서 다시 실행할 수 있는지 여부.
* `canCut` Boolean - 렌더러에서 잘라내기를 실행할 수 있는지 여부.
* `canCopy` Boolean - 렌더러에서 복사를 실행할 수 있는지 여부.
* `canPaste` Boolean - 렌더러에서 붙여넣기를 실행할 수 있는지 여부.
* `canDelete` Boolean - 렌더러에서 삭제를 실행할 수 있는지 여부.
* `canSelectAll` Boolean - 렌더러에서 모두 선택을 실행할 수 있는지 여부.
표시합니다.
* `canUndo` Boolean - 렌더러에서 실행 취소할 수 있는지 여부.
* `canRedo` Boolean - 렌더러에서 다시 실행할 수 있는지 여부.
* `canCut` Boolean - 렌더러에서 잘라내기를 실행할 수 있는지 여부.
* `canCopy` Boolean - 렌더러에서 복사를 실행할 수 있는지 여부.
* `canPaste` Boolean - 렌더러에서 붙여넣기를 실행할 수 있는지 여부.
* `canDelete` Boolean - 렌더러에서 삭제를 실행할 수 있는지 여부.
* `canSelectAll` Boolean - 렌더러에서 모두 선택을 실행할 수 있는지 여부.
새로운 컨텍스트 메뉴의 제어가 필요할 때 발생하는 이벤트입니다.
@ -417,9 +417,7 @@ Returns:
Returns:
* `event` Event
* `devices` [Objects]
* `deviceName` String
* `deviceId` String
* `devices` [BluetoothDevice[]](structures/bluetooth-device.md)
* `callback` Function
* `deviceId` String
@ -611,7 +609,7 @@ CSS 코드를 현재 웹 페이지에 삽입합니다.
* `code` String
* `userGesture` Boolean (optional)
* `callback` Function (optional) - 스크립트의 실행이 완료되면 호출됩니다.
* `result`
* `result` Any
페이지에서 자바스크립트 코드를 실행합니다.
@ -638,6 +636,7 @@ CSS 코드를 현재 웹 페이지에 삽입합니다.
#### `contents.getZoomFactor(callback)`
* `callback` Function
* `zoomFactor` Number
현재 줌 수치 값을 요청합니다. `callback``callback(zoomFactor)` 형태로 호출됩니다.
@ -651,6 +650,7 @@ CSS 코드를 현재 웹 페이지에 삽입합니다.
#### `contents.getZoomLevel(callback)`
* `callback` Function
* `zoomLevel` Number
현재 줌 수준 값을 요청합니다. `callback``callback(zoomLevel)` 형태로 호출됩니다.
@ -779,6 +779,7 @@ console.log(requestId)
#### `contents.hasServiceWorker(callback)`
* `callback` Function
* `hasWorker` Boolean
ServiceWorker가 등록되어있는지 확인하고 `callback`에 대한 응답으로 boolean 값을
반환합니다.
@ -786,6 +787,7 @@ ServiceWorker가 등록되어있는지 확인하고 `callback`에 대한 응답
#### `contents.unregisterServiceWorker(callback)`
* `callback` Function
* `success` Boolean
ServiceWorker가 존재하면 모두 등록을 해제하고 JS Promise가 만족될 때 `callback`
대한 응답으로 boolean을 반환하거나 JS Promise가 만족되지 않을 때 `false`를 반환합니다.
@ -817,6 +819,8 @@ ServiceWorker가 존재하면 모두 등록을 해제하고 JS Promise가 만족
* `landscape` Boolean - landscape을 위해선 `true`를, portrait를 위해선 `false`
사용합니다.
* `callback` Function - `(error, data) => {}`
* `error` Error
* `data` Buffer
Chromium의 미리보기 프린팅 커스텀 설정을 이용하여 윈도우의 웹 페이지를 PDF로
프린트합니다.
@ -1034,6 +1038,8 @@ Input `event`를 웹 페이지로 전송합니다.
* `onlyDirty` Boolean (optional) - 기본값은 `false`입니다.
* `callback` Function
* `frameBuffer` Buffer
* `dirtyRect` [Rectangle](structures/rectangle.md)
캡처된 프레임과 프레젠테이션 이벤트를 구독하기 시작합니다. `callback`
프레젠테이션 이벤트가 발생했을 때 `callback(frameBuffer, dirtyRect)` 형태로
@ -1055,7 +1061,7 @@ Input `event`를 웹 페이지로 전송합니다.
#### `contents.startDrag(item)`
* `item` object
* `item` Object
* `file` String
* `icon` [NativeImage](native-image.md)

View file

@ -81,13 +81,27 @@ webFrame.setSpellCheckProvider('en-US', true, {
현재 페이지 콘텐츠의 보안 정책에 상관없이 `scheme`로부터 리소스가 로드됩니다.
### `webFrame.registerURLSchemeAsPrivileged(scheme)`
### `webFrame.registerURLSchemeAsPrivileged(scheme[, options])`
* `scheme` String
* `scheme` String
* `options` Object(optional)
* `secure` Boolean - (optional) 기본값 참.
* `bypassCSP` Boolean - (optional) 기본값 참.
* `allowServiceWorkers` Boolean - (optional) 기본값 참.
* `supportFetchAPI` Boolean - (optional) 기본값 참.
* `corsEnabled` Boolean - (optional) 기본값 참.
`scheme`를 보안된 스킴으로 등록합니다. 리소스에 대해 보안 정책을 우회하며,
ServiceWorker의 등록과 fetch API를 사용할 수 있도록 지원합니다.
등록에서 그것을 빼려면 `false` 값으로 옵션을 지정하세요.
콘텐츠 보안 정책을 우회하지 않고, 특권 스킴을 등록하는 예:
```javascript
const {webFrame} = require('electron')
webFrame.registerURLSchemeAsPrivileged('foo', { bypassCSP: false })
```
### `webFrame.insertText(text)`
* `text` String
@ -107,6 +121,7 @@ ServiceWorker의 등록과 fetch API를 사용할 수 있도록 지원합니다.
### `webFrame.getResourceUsage()`
Returns `Object`:
* `images` [MemoryUsageDetails](structures/memory-usage-details.md)
* `cssStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md)
* `xslStyleSheets` [MemoryUsageDetails](structures/memory-usage-details.md)

View file

@ -187,6 +187,21 @@ API를 사용할 수 있습니다. 이를 지정하면 내부에서 로우레벨
"on"으로 지정하면 페이지에서 새로운 창을 열 수 있도록 허용합니다.
### `webpreferences`
```html
<webview src="https://github.com" webpreferences="allowDisplayingInsecureContent, javascript=no"></webview>
```
웹뷰에 설정될 웹 환경설정을 나타내는 `,` 로 구분된 문자열의 목록입니다.
지원되는 환경설정 문자열의 전체 목록은
[BrowserWindow](browser-window.md#new-browserwindowoptions) 에서 찾을 수
있습니다.
문자열은 `window.open` 의 기능 문자열과 같은 형식을 따릅니다. 이름만 있으면
`true` 불린 값이 주어집니다. 환경설정은 뒤에 값이 오는 `=` 을 넣어서 다른 값을
설정할 수 있습니다. 특별한 값 `yes``1``true` 로 해석되고, `no``0`
`false` 로 해석됩니다.
### `blinkfeatures`
```html
@ -338,7 +353,7 @@ Webview에 웹 페이지 `url`을 로드합니다. `url`은 `http://`, `file://`
* `code` String
* `userGesture` Boolean
* `callback` Function (optional) - 스크립트의 실행이 완료되면 호출됩니다.
* `result`
* `result` Any
페이지에서 자바스크립트 코드를 실행합니다.

View file

@ -25,6 +25,7 @@
옵션이어야 합니다.
**참고:**
* Node 통합 기능은 열린 `window` 에서 부모 윈도우가 해당 옵션이 비활성화
되어있는 경우 항상 비활성화됩니다.
* `features` 에 있는 (Chromium 또는 Electron 에 의해 처리되지 않는) 비표준

View file

@ -0,0 +1,110 @@
# 릴리즈
이 문서는 Electron 의 새버전 출시 절차를 설명합니다.
## 릴리즈 노트 편집
현재 절차는 로컬 파일을 유지하고 병합된 풀 요청과 같은 중요한 변화의 추척을
보존하는 것 입니다. 노트 형식에 대한 예제는, [릴리즈 페이지]에서 이전 릴리즈를
보세요.
## 임시 브랜치 생성
`release` 이름의 새 브랜치를 `master` 로부터 생성합니다.
```sh
git checkout master
git pull
git checkout -b release
```
이 브랜치는 임시 릴리즈 브랜치가 생성되고 CI 빌드가 완료되는 동안 아무도 모르는
PR 병합을 방지하기위한 예방조치로써 생성됩니다.
## 버전 올리기
`major`, `minor`, `patch` 를 인수로 전달하여, `bump-version` 스크립트를
실행하세요:
```sh
npm run bump-version -- patch
git push origin HEAD
```
이것은 여러 파일의 버전 번호를 올릴 것 입니다. 예시로 [이 범프 커밋]을 보세요.
대부분의 릴리즈는 `patch` 수준이 될 것입니다. Chrome 또는 다른 주요 변화는
`minor` 를 사용해야합니다. 자세한 정보는, [Electron 버전 관리]를 보세요.
## 릴리즈 초안 편집
1. [릴리즈 페이지]에 가면 릴리즈 노트 초안과 자리 표시자로써 릴리즈 노트를 볼 수
있습니다.
1. 릴리즈를 편집하고 릴리즈 노트를 추가하세요.
1. 'Save draft' 를 클릭하세요. **'Publish release' 를 누르면 안됩니다!**
1. 모든 빌드가 통과할 때 까지 기다리세요. :hourglass_flowing_sand:
## 임시 브랜치 병합
임시를 마스터로 머지 커밋 생성없이 병합합니다.
```sh
git merge release master --no-commit
git push origin master
```
실패하면, 마스터로 리베이스하고 다시 빌드합니다:
```sh
git pull
git checkout release
git rebase master
git push origin HEAD
```
## 로컬 디버그 빌드 실행
당신이 실제로 원하는 버전을 구축하고 있는지 확인하기 위해 로컬 디버그 빌드를
실행합니다. 때때로 새 버전을 릴리즈하고 있다고 생각하지만, 아닌 경우가 있습니다.
```sh
npm run build
npm start
```
창이 현재 업데이트된 버전을 표시하는지 확인하세요.
## 환경 변수 설정
릴리즈를 게시하려면 다음 환경 변수를 설정해야합니다. 이 자격증명에 대해 다른 팀
구성원에게 문의하세요.
- `ELECTRON_S3_BUCKET`
- `ELECTRON_S3_ACCESS_KEY`
- `ELECTRON_S3_SECRET_KEY`
- `ELECTRON_GITHUB_TOKEN` - "저장소" 영역에 대한 개인 접근 토큰.
이것은 한번만 수행해야합니다.
## 릴리즈 게시
이 스크립트는 바이너리를 내려받고 네이티브 모듈 구축을 위해 node-gyp 으로
윈도우에서 사용되는 노드 헤더와 .lib 링커를 생성합니다.
```sh
npm run release
```
참고: 많은 파이썬의 배포판들은 여전히 오래된 HTTPS 인증서와 함께 제공됩니다.
`InsecureRequestWarning` 를 볼 수 있지만, 무시해도 됩니다.
## 임시 브랜치 삭제
```sh
git checkout master
git branch -D release # 로컬 브랜치 삭제
git push origin :release # 원격 브랜치 삭제
```
[릴리즈 페이지]: https://github.com/electron/electron/releases
[이 범프 커밋]: https://github.com/electron/electron/commit/78ec1b8f89b3886b856377a1756a51617bc33f5a
[Electron 버전 관리]: ../tutorial/electron-versioning.md

View file

@ -299,6 +299,29 @@ let win = new BrowserWindow()
win.setOverlayIcon('path/to/overlay.png', 'Description for overlay')
```
## 프레임 깜빡이기 (윈도우즈)
윈도우즈에서 사용자의 관심을 끌기 위해ㅣ 작업표시줄 버튼을 강조할 수 있습니다.
이것은 macOS 의 독 아이콘을 튕기는 것과 유사합니다.
MSDN에서 인용하자면 (영문):
> Typically, a window is flashed to inform the user that the window requires
> attention but that it does not currently have the keyboard focus.
BrowserWindow 작업표시줄 버튼을 깜빡이려면,
[BrowserWindow.flashFrame][flashframe] API 를 사용하면됩니다:
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow()
win.once('focus', () => win.flashFrame(false))
win.flashFrame(true)
```
`flashFrame` 메소드를 `false` 인자로 호출하여 깜빡임을 중단시키는 것을
잊지마세요. 위의 예제에서, 윈도우가 포커스되었을 때 호출합니다. 그러나 타임아웃
또는 다른 이벤트에서 비활성화할 수 있습니다.
## 대표 파일 제시 (macOS)
macOS는 창에서 대표 파일을 설정할 수 있습니다. 타이틀바에서 파일 아이콘이 있고, 사용자가
@ -364,3 +387,4 @@ ipcMain.on('ondragstart', (event, filePath) => {
[tray-balloon]: ../api/tray.md#traydisplayballoonoptions-windows
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
[notification-spec]: https://developer.gnome.org/notification-spec/
[flashframe]: ../api/browser-window.md#winflashframeflag

View file

@ -1,53 +1,54 @@
# 보안, 네이티브 호환성, 그리고 신뢰성
웹 개발자로써, 우리는 일반적으로 브라우저의 강력한 웹 보안을 잘 이용해왔습니다 - 작성한
코드에 관련된 보안 문제는 아주 적었습니다. 우리는 웹 사이트의 샌드박스안에서 허용된
상당히 제한된 권한과 기능에 의존해왔으며, 우리는 새로운 보안 위협에 대해 발 빠르게
대응할 수 있는 엔지니어들로 이루어진 커다란 팀으로부터 만들어진 브라우저를 사용자들이
마음 놓고 즐길 것이라고 믿어왔습니다.
웹 개발자로써, 우리는 일반적으로 브라우저의 강력한 웹 보안을 잘 이용해왔습니다
- 작성한 코드에 관련된 보안 문제는 아주 적었습니다. 우리는 웹 사이트의
샌드박스안에서 허용된 상당히 제한된 권한과 기능에 의존해왔으며, 우리는 새로운
보안 위협에 대해 발 빠르게 대응할 수 있는 엔지니어들로 이루어진 커다란
팀으로부터 만들어진 브라우저를 사용자들이 마음 놓고 즐길 것이라고 믿어왔습니다.
하지만 Electron을 사용하여 작업한다면, Electron은 웹 브라우저가 아니라는 것을 기억해
두어야 합니다. Electron은 친근한 웹 기술을 사용하여 풍부한 기능의 데스크톱
하지만 Electron을 사용하여 작업한다면, Electron은 웹 브라우저가 아니라는 것을
기억해야 합니다. Electron은 친근한 웹 기술을 사용하여 풍부한 기능의 데스크톱
애플리케이션을 만들 수 있도록 해주지만 그만큼 코드가 더 큰 힘을 사용합니다.
JavaScript가 파일 시스템, 유저 쉘, 그외 여러가지 기능에 접근할 수 있습니다. 이러한
능력은 높은 퀄리티를 가진 네이티브 애플리케이션을 개발할 수 있도록 해주지만 코드에
부여된 추가적인 기능만큼 고유한 보안 문제가 발생할 가능성이 있습니다.
자바스크립트가 파일 시스템, 유저 쉘, 그외 여러가지 기능에 접근할 수 있습니다.
이러한 능력은 높은 퀄리티를 가진 네이티브 애플리케이션을 개발할 수 있도록
해주지만 코드에 부여된 추가적인 기능만큼 고유한 보안 문제가 발생할 가능성이
있습니다.
이를 염두해두고, 신뢰할 수 없는 출처의 임의의 콘텐츠를 표시할 때 Electron에서
자체적으로 처리하지 않는 심각한 보안 문제를 야기할 수 있다는 점을 주의해야 합니다.
실제로도, 가장 유명한 Electron 애플리케이션들은 (Atom, Slack, Visual Studio Code,
등) 주로 로컬 콘텐츠를 (또는 Node 통합이 제외된 신뢰된, 보안된 원격 콘텐츠) 사용합니다
- 만약 애플리케이션이 온라인 출처에서 가져온 코드를 실행한다면, 그 코드가 악성 코드가
아닌지 판별하는 것은 본인의 책임입니다.
자체적으로 처리하지 않는 심각한 보안 문제를 야기할 수 있다는 점을 주의해야
합니다. 실제로도, 가장 유명한 Electron 애플리케이션들은 (Atom, Slack, Visual
Studio Code, 등) 주로 로컬 콘텐츠를 (또는 Node 통합이 제외된 신뢰된, 보안된 원격
콘텐츠) 사용합니다 - 만약 애플리케이션이 온라인 출처에서 가져온 코드를
실행한다면, 그 코드가 악성 코드가 아닌지 판별하는 것은 본인의 책임입니다.
## Chromium 보안 문제와 업그레이드
Electron이 새로운 버전의 Chromium을 가능한 한 빠르게 지원하려고 노력하지만,
개발자는 이러한 업그레이딩 작업은 매우 힘든 작업이라는 것을 알아야 합니다 - 각 관련된
수십에서 심지어 백자리 개수의 파일들을 손수 수정해야 합니다. 주어진 자원과 현재
기여도를 생각한다면, Electron은 항상 최신 버전의 Chromium을 유지하지 못할 수 있으며,
며칠부터 몇 주까지 더 걸릴 수 있습니다.
개발자는 이러한 업그레이딩 작업은 매우 힘든 작업이라는 것을 알아야 합니다 - 각
관련된 수십에서 심지어 백자리 개수의 파일들을 손수 수정해야 합니다. 주어진
자원과 현재 기여도를 생각한다면, Electron은 항상 최신 버전의 Chromium을 유지하지
못할 수 있으며, 며칠부터 몇 주까지 더 걸릴 수 있습니다.
현재 Chromium 구성 요소를 업데이트하는 시스템은 우리가 사용할 수 있는 자원과 이
프레임워크를 기반으로 구축된 대부분의 애플리케이션이 요구하는 것 사이에서 적절한 균형을
유지하고 있다고 느끼고 있습니다. 우리는 확실히 Electron 위에 무언가를 만드는 사람들의
사용 사례에 대한 자세한 내용을 듣는 것에 관심이 있습니다. 이러한 노력을 지원하는 Pull
request와 기여는 언제나 환영합니다.
프레임워크를 기반으로 구축된 대부분의 애플리케이션이 요구하는 것 사이에서 적절한
균형을 유지하고 있다고 느끼고 있습니다. 우리는 확실히 Electron 위에 무언가를
만드는 사람들의 사용 사례에 대한 자세한 내용을 듣는 것에 관심이 있습니다. 이러한
노력을 지원하는 Pull 요청과 기여는 언제나 환영합니다.
## 위 조언 무시하기
원격 위치에서 받아온 코드를 로컬에서 실행하는 경우 언제나 보안 문제가 존재합니다.
예를 들어, 원격 웹 사이트가 브라우저 윈도우에서 표시될 때를 생각해볼 때, 만약 공격자가
어떠한 방법으로 웹 페이지의 콘텐츠를 변경하는 경우 (소스를 직접적으로 공격하거나
애플리케이션과 실질적인 위치 사이에서 공격하는 등), 공갹자는 사용자의 기기에서 네이티브
코드를 실행할 수 있습니다.
원격 위치에서 받아온 코드를 로컬에서 실행하는 경우 언제나 보안 문제가
존재합니다. 예를 들어, 원격 웹 사이트가 브라우저 윈도우에서 표시될 때를 생각해볼
때, 만약 공격자가 어떠한 방법으로 웹 페이지의 콘텐츠를 변경하는 경우 (소스를
직접적으로 공격하거나 애플리케이션과 실질적인 위치 사이에서 공격하는 등),
공격자는 사용자의 기기에서 네이티브 코드를 실행할 수 있습니다.
> :warning: 어떠한 상황에서도 원격 코드를 로드하고 실행할 땐 Node 통합 기능을
비활성화하고, 로컬 파일만 (애플리케이션 패키지 내부에 포함된) Node 코드를 실행시킬 수
있도록 하는 것이 좋습니다. 원격 콘텐츠를 표시할 땐, 항상 `webview` 사용하고
`nodeIntegration`이 비활성화되어있는지 확인하세요.
> :경고: 어떠한 상황에서도 원격 코드를 로드하고 실행할 땐 Node 통합 기능을
비활성화하고, 로컬 파일만 (애플리케이션 패키지 내부에 포함된) Node 코드를
실행시킬 수 있도록 하는 것이 좋습니다. 원격 콘텐츠를 표시할 땐, 항상 `webview`
사용하고 `nodeIntegration`이 비활성화되어있는지 확인하세요.
#### 체크 리스트
#### 확인 사항
이 리스트는 완벽하지 않습니다, 하지만 최소한 다음 사항은 확인하는 것이 좋습니다:
@ -64,12 +65,33 @@ request와 기여는 언제나 환영합니다.
* `allowRunningInsecureContent``true`로 설정하지 마세요.
* 무엇을 하고 있는지 확실히 알고 있지않는 이상 `experimentalFeatures` 또는
`experimentalCanvasFeatures`를 활성화하지 마세요.
* 무엇을 하고 있는지 확실히 알고 있지않는 이상 `blinkFeatures`를 활성화하지 마세요.
* WebViews: `nodeintegration``false`로 설정하세요.
* 무엇을 하고 있는지 확실히 알고 있지않는 이상 `blinkFeatures`를 활성화하지
마세요.
* WebViews: `nodeintegration` 속성을 추가하지마세요.
* WebViews: `disablewebsecurity`를 사용하지 마세요.
* WebViews: `allowpopups`를 사용하지 마세요.
* WebViews: 원격 CSS/JS와 `insertCSS` 또는 `executeJavaScript`를 함께 사용하지
마세요.
다시 말하지만, 이 리스트는 그저 위험을 최소화할 뿐이며 완전히 제거하지 않습니다. 만약
목적이 그저 웹 사이트를 보여주는 것이라면 일반 웹 브라우저가 더 안전한 방법입니다.
다시 말하지만, 이 리스트는 그저 위험을 최소화할 뿐이며 완전히 제거하지 않습니다.
만약 목적이 그저 웹 사이트를 보여주는 것이라면 일반 웹 브라우저가 더 안전한
방법입니다.
## Buffer Global
노드의 [Buffer](https://nodejs.org/api/buffer.html) 클래스는 현재
`nodeintegration` 속성이 추가되지 않은 경우에도 전역으로 사용가능합니다.
`preload` 스크립트에서 다음을 수행하여 앱에서 이것을 삭제할 수 있습니다:
```js
delete global.Buffer
```
많은 라이브러리들이 다음을 통해 직접 요구하는 대신 전역을 기대하기 때문에 이것을
삭제하면 사전에 설치된 스크립트와 앱에서 사용되는 Node 모듈이 깨질 수 있습니다.
```js
const {Buffer} = require('buffer')
```
전역 `Buffer` 는 향후 Electron 주 버전에서 제거될 것 입니다.

View file

@ -75,3 +75,7 @@ Pepper 플래시 플러그인의 구조는 Electron과 일치해야 합니다. W
Windows에선 `--ppapi-flash-path`로 전달되는 경로의 분리자로 `\`를 사용해야 합니다.
POSIX-스타일 경로는 작동하지 않을 것입니다.
RTMP 를 사용한 미디어 스트리밍같은 일부 작업의 경우 플레이어의 `.swf` 파일에
폭넓은 권한을 부여할 필요가 있습니다. 그러기 위한 한가지 방법은,
[nw-flash-trust](https://github.com/szwacz/nw-flash-trust)를 사용하는 것입니다.

View file

@ -9,7 +9,7 @@ selecione a *tag* que corresponde à sua versão.
## FAQ
Existem muitas perguntas comuns que são feitas, verifique antes de criar uma issue.
* [Electron FAQ](../../docs/faq.md)
* [Electron FAQ](faq.md)
## Guias
@ -40,15 +40,15 @@ Existem muitas perguntas comuns que são feitas, verifique antes de criar uma is
### Elementos DOM Personalizados:
* [Objeto `File`](../../docs-translations/pt-BR/api/file-object.md)
* [Objeto `File`](api/file-object.md)
* [Tag `<webview>`](../../docs/api/web-view-tag.md)
* [Função `window.open`](../../docs/api/window-open.md)
* [Função `window.open`](api/window-open.md)
### Módulos para o Processo Principal:
* [app](api/app.md)
* [autoUpdater](api/auto-updater.md)
* [BrowserWindow](../../docs/api/browser-window.md)
* [BrowserWindow](api/browser-window.md)
* [contentTracing](../../docs/api/content-tracing.md)
* [dialog](../../docs/api/dialog.md)
* [globalShortcut](../../docs/api/global-shortcut.md)
@ -85,5 +85,5 @@ Existem muitas perguntas comuns que são feitas, verifique antes de criar uma is
* [Visão Geral do Build](../../docs/development/build-system-overview.md)
* [Instrução de Build (Mac)](development/build-instructions-osx.md)
* [Instrução de Build (Windows)](../../docs/development/build-instructions-windows.md)
* [Instrução de Build (Linux)](../../docs/development/build-instructions-linux.md)
* [Instrução de Build (Linux)](development/build-instructions-linux.md)
* [Configurando um Symbol Server no Debugger](../../docs/development/setting-up-symbol-server.md)

View file

@ -597,7 +597,7 @@ Se a barra de menu já estiver visível, chamar `setAutoHideMenuBar(true)` não
Retorna um boolean indicando se a barra de menu se esconde automaticamente.
### `win.setMenuBarVisibility(visible)`
### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` Boolean

View file

@ -1,67 +1,96 @@
# The `window.open` function
# Função `window.open`
Qunado `window.open` é chamado para criar uma nova janela de uma pagina web uma nova instância de `BrowserWindow` será criado para a `url` e um proxy será devolvido para o `windows.open`, para permitir que a página tenha limitado controle sobre ele.
> Abre uma nova janela e carrega uma URL.
O proxy tem funcionalidade limitada padrão implementada para ser compatível com as páginas web tradicionais.
Para controle total da nova janela você deveria criar um `BrowserWindow` diretamente
Quando `window.open` é chamada para criar uma nova janela de uma página web, uma
nova instância de `BrowserWindow` será criada para a `url` e um proxy será
devolvido para o `window.open` para permitir que a página tenha controle
limitado sobre ele.
O proxy tem uma funcionalidade padrão implementada de forma limitada para ser
compatível com páginas web tradicionais. Para ter controle total de uma nova
janela, você deverá criar diretamente um `BrowserWindow`.
The newly created `BrowserWindow` will inherit parent window's options by
default, to override inherited options you can set them in the `features`
string.
O `BrowserWindow` recém-criado herdará as opções da janela pai por padrão. Para
substituir as opções herdadas, você poderá defini-las na string `features`.
O recém-criado `BrowserWindow` herdará as opções da janela pai por padrão, para substituir as opções herdadas você pode definilos no `features`(string).
### `window.open(url[, frameName][, features])`
* `url` String
* `frameName` String (opcional)
* `features` String (opcional)
Cria uma nova janela e retorna uma instância da classe `BrowserWindowProxy'.
Retorna `BrowserWindowProxy` - Cria uma nova janela e retorna uma instância da
classe `BrowserWindowProxy`.
A string `features` segue o formato padrão do browser, mas cada recurso (feature) tem que ser um campo de opções do `BrowserWindow`.
A string `features` segue o formato de um navegador padrão, mas cada recurso
(feature) tem de ser um campo das opções do `BrowserWindow`.
**Notas:**
* Integração com Node sempre estará desativada no `window` aberto se ela
estiver desativada na janela pai.
* Recursos fora do padrão (que não são manipulados pelo Chromium ou pelo
Electron) fornecidos em `features` serão passados para qualquer manipulador
de eventos `new-window` do `webContent` registrado no argumento
`additionalFeatures`.
### `window.opener.postMessage(message, targetOrigin)`
* `message` String
* `targetOrigin` String
Envia uma mensagem para a janela pai com a origem especificada ou `*` preferência de origem não especificada.
Sends a message to the parent window with the specified origin or `*`
origin preference.
Envia uma mensagem para a janela pai com a origem especificada ou `*` para
nenhuma preferência de origem.
## Class: BrowserWindowProxy
## Classe: BrowserWindowProxy
O objeto `BrowserWindowProxy` é retornado de `window.open` e fornece uma funcionalidade limitada para a janela filha.
> Manipula a janela de navegador filha
### `BrowserWindowProxy.blur()`
O objeto `BrowserWindowProxy` é retornado de `window.open` e fornece uma
funcionalidade limitada para a janela filha.
### Métodos de Instância
O objeto `BrowserWindowProxy` possui os seguintes métodos de instância:
#### `win.blur()`
Remove o foco da janela filha.
### `BrowserWindowProxy.close()`
#### `win.close()`
Forçadamente fecha a janela filha sem chamar o evento de descarregamento.
Fecha forçadamente a janela filha sem chamar seu evento de descarregamento.
### `BrowserWindowProxy.closed`
Define como true após a janela filha ficar fechada.
### `BrowserWindowProxy.eval(code)`
#### `win.eval(code)`
* `code` String
Avalia o código na jánela filha.
Avalia o código na janela filha.
### `BrowserWindowProxy.focus()`
#### `win.focus()`
Concentra-se a janela filha (traz a janela para frente)
### `BrowserWindowProxy.postMessage(message, targetOrigin)`
Foca na janela filha (traz a janela para frente).
#### `win.print()`
Invoca o diálogo de impressão na janela filha.
#### `win.postMessage(message, targetOrigin)`
* `message` String
* `targetOrigin` String
Sends a message to the child window with the specified origin or `*` for no
origin preference.
Envia uma mensagem para a janela filha com a origem especificada ou `*` para
nenhuma preferência de origem.
In addition to these methods, the child window implements `window.opener` object
with no properties and a single method.
Além desses métodos, a janela filha implementa o objeto `window.opener` sem
propriedades e com apenas um método.
### Propriedades de Instância
O objeto `BrowserWindowProxy` possui as seguintes propriedades de instância:
#### `win.closed`
Um booleano que é definido como true após a janela filha ser fechada.

View file

@ -52,7 +52,7 @@ electron/resources/
└── app.asar
```
Больше деталей можно найти в [инстуркции по упаковке приложения](application-packaging.md).
Больше деталей можно найти в [инструкции по упаковке приложения](application-packaging.md).
## Ребрендирование скачанных исполняемых файлов

View file

@ -720,7 +720,7 @@ windows上句柄类型为 `HWND` macOS `NSView*` Linux `Window`.
返回 boolean,窗口的菜单栏是否可以自动隐藏.
### `win.setMenuBarVisibility(visible)`
### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` Boolean

View file

@ -0,0 +1,9 @@
# Certificate 物件 (憑證)
* `data` 字串 - PEM 加密資料。
* `issuerName` 字串 - 憑證發行者的名字。
* `subjectName` 字串 - 憑證使用者的名字。
* `serialNumber` 字串 - 憑證序號。
* `validStart` 數字 - 憑證開始日期,值為 UNIX 時間。
* `validExpiry` 數字 - 憑證結束日期,值為 UNIX 時間。
* `fingerprint` 字串 - 憑證指紋。

View file

@ -0,0 +1,11 @@
# Cookie 物件
* `name` 字串 - cookie 的名字。
* `value` 字串 - cookie 的值。
* `domain` 字串 - cookie 的域名。
* `hostOnly` 字串 - cookie 是否為 Host-Only.。
* `path` 字串 - cookie 的路徑。
* `secure` 布林 - cookie 的網域是否安全 https)。
* `httpOnly` 布林 - cookie 是否只能運行在 HTTP。
* `session` 布林 - cookie 為 短期 session 或者 長期 cookie若是長期 cookie 得包含一個截止日期。
* `expirationDate` 雙精度浮點數 (可選) - cookie 的截止日期,當 `session` 設定為 時可用,值為 UNIX時間。

View file

@ -0,0 +1,8 @@
# MemoryUsageDetails 物件
* `count` 數字
* `size` 數字
* `liveSize` 數字
* `decodedSize` 數字
* `purgedSize` 數字
* `purgeableSize` 數字

View file

@ -0,0 +1,8 @@
# Task 物件
* `program` 字串 - 程式執行的路徑,通常你應該指定 `process.execPath`,此值為當前程式執行的路徑。
* `arguments` 字串 - `program` 在命令列下執行的附加參數。
* `title` 字串 - JumpList 內顯示的標題。
* `description` 字串 - 關於此物件的描述。
* `iconPath` 字串 - 此物件的 icon 路徑,被顯示在 JumpList 中,通常你可以指定 `process.execPath`去顯示當前物件的 icon 。
* `iconIndex` 數字 - icon 的索引,如果一個檔案包由兩個或以上的的 icon, 設定此值去指定 icon, 如果檔案內只有一個 icon, 此值為 0 。

View file

@ -0,0 +1,46 @@
# 貢獻者行為守則契約
## 我們的承諾
為了營造一個開放和溫馨的環境,我們作為貢獻者和維護者,承諾對每個參與我們的項目和社區的人,提供不受騷擾的環境,無論年齡、身體大小、殘疾、自我認同種族、性別認同和表達、經驗水準、國籍,個人外貌,天生種族,宗教或生理性別和性取向。
## 我們的標準
有助於創造積極環境的行為包括:
* 使用歡迎和包容性的語言
* 尊重不同的觀點和經驗
* 優雅地接受建設性的批評
* 專住在為社群最好的事情上
* 顯示對其他社區成員的同情
參與者不被許可的行為例子包括:
* 使用性別化語言或圖像以及不歡迎的性別關注或其他更進一步的行為
* 毀謗、侮辱、貶損的評論以及個人或政治攻擊
* 公共或私人騷擾
* 未經明確許可,發布他人的個資,如住址或電子信箱
* 其他可以合理地認為在專業環境中不合適的行為
## 我們的責任
專案維護者負責澄清可接受的行為標準,並且應該對任何不可接受的行為採取適當且公平的糾正措施。
專案維護者有權利和責任刪除、編輯或拒絕與本行為準則不一致的評論、提交、代碼,維基編輯,問題和其他不在此列的貢獻。甚至暫時或永久禁止任何被認為是不當、威脅、攻擊性或有害的參與者。
## 範圍
當個人代表專案或其社群時,本行為準則適用於專案範圍或公共空間。代表專案或社群的例子包括使用官方電子郵件、透過官方社群帳號發文、或在線上或離線的活動擔任指定代表。專案的表現行為可由專案維護者進一步定義和澄清。
## 強制執行
濫用、騷擾或其他不可接受行為的實例可向專案團隊 [electron@github.com](mailto:electron@github.com) 報告。所有投訴將被審查和調查,並在被認為必要和適合情況下做出回應。專案團隊有義務對事件提報者保密。具體執行政策的進一步細節可以單獨公佈。
未真誠遵守或實施行為準則的專案維護者可能會面臨專案領導層成員所決定的暫時性或永久性影響。
## 來源
本行為準則改編自 [Contributor Covenant][homepage], 1.4版, 可從 [http://contributor-covenant.org/version/1/4][version] 獲得
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View file

@ -0,0 +1,74 @@
# Electron約定
:+1::tada: 首先,感謝抽出時間做出貢獻的每一個人! :tada::+1:
該項目遵守貢獻者約定 [code of conduct](CODE_OF_CONDUCT.md)。
我們希望貢獻者能遵守此約定。如果有發現任何不被接受的行為請回報至electron@github.com(PS:請用英語)。
下在是一些用於改進Electron的指南。
這些只是指導方針,而不是規則,做出你認為最適合的判斷,並隨時
在 pull request 中提出對該文件的更改。
## 提交 Issues
* 你可以在此創建一個 issue [here](https://github.com/electron/electron/issues/new)
但在此之前,請閱讀以下注意事項,其中應包含盡可能多的細節。
如果可以的話,請包括:
* 你所使用的 Electron 版本
* 你所使用的系統
* 如果適用,請包括:你做了什麼時發生了問題,以及你所預期的結果。
* 其他有助於解決你的 issue 的選項:
* 截圖和動態GIF
* 終端機和開發工具中的錯誤訊息或警告。
* 執行 [cursory search](https://github.com/electron/electron/issues?utf8=✓&q=is%3Aissue+)
檢查是否已存在類似問題
## 提交 Pull Requests
* 可以的話,在 pull request 包含截圖和動態GIF。
* 遵守 JavaScript, C++, and Python [coding style defined in docs](/docs/development/coding-style.md).
* 使用 [Markdown](https://daringfireball.net/projects/markdown) 撰寫文件。
請參考 [Documentation Styleguide](/docs/styleguide.md).
* 使用簡單明瞭的提交訊息。請參考 [Commit Message Styleguide](#git-commit-messages).
## 文件樣式
### 通用代碼
* 以空行做文件結尾。
* 按照以下順序載入模組:
* 添加 Node Modules (參考 `path`)
* 添加 Electron Modules (參考 `ipc`, `app`)
* 本地模組(使用相對路徑)
* 按照以下的順序排序類別(class)的屬性:
* 類別的方法和屬性 (方法以 `@` 作為開頭)
* 實體(Instance)的方法和屬性
* 避免使用平台相依代碼:
* 使用 `path.join()` 來連接檔案名稱。
* 當需要使用臨時目錄時,使用 `os.tmpdir()` 而不是 `/tmp`
* 在 function 結尾使用明確的 `return`
* 不要使用 `return null`, `return undefined`, `null`, 或 `undefined`
### Git 提交訊息 (鑑於進行Git提交時需要英文書寫此處暫不翻譯)
* Use the present tense ("Add feature" not "Added feature")
* Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
* Limit the first line to 72 characters or less
* Reference issues and pull requests liberally
* When only changing documentation, include `[ci skip]` in the commit description
* Consider starting the commit message with an applicable emoji:
* :art: `:art:` when improving the format/structure of the code
* :racehorse: `:racehorse:` when improving performance
* :non-potable_water: `:non-potable_water:` when plugging memory leaks
* :memo: `:memo:` when writing docs
* :penguin: `:penguin:` when fixing something on Linux
* :apple: `:apple:` when fixing something on macOS
* :checkered_flag: `:checkered_flag:` when fixing something on Windows
* :bug: `:bug:` when fixing a bug
* :fire: `:fire:` when removing code or files
* :green_heart: `:green_heart:` when fixing the CI build
* :white_check_mark: `:white_check_mark:` when adding tests
* :lock: `:lock:` when dealing with security
* :arrow_up: `:arrow_up:` when upgrading dependencies
* :arrow_down: `:arrow_down:` when downgrading dependencies
* :shirt: `:shirt:` when removing linter warnings

View file

@ -0,0 +1,77 @@
[![Electron Logo](http://electron.atom.io/images/electron-logo.svg)](http://electron.atom.io/)
[![Travis Build Status](https://travis-ci.org/electron/electron.svg?branch=master)](https://travis-ci.org/electron/electron)
[![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/kvxe4byi7jcxbe26/branch/master?svg=true)](https://ci.appveyor.com/project/Atom/electron)
[![devDependency Status](https://david-dm.org/electron/electron/dev-status.svg)](https://david-dm.org/electron/electron?type=dev)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
Electron框架讓你可以用JavaScript, HTML 和 CSS 編寫跨平台的應用程式。
它是基於[Node.js](https://nodejs.org/)和[Chromium](http://www.chromium.org)
並且被[Atom editor](https://github.com/atom/atom)及許多其他的[apps](http://electron.atom.io/apps)所使用。
請關注[@ElectronJS](https://twitter.com/electronjs)的Twitter以獲得重要公告。
該項目遵守貢獻者約定 [code of conduct](CODE_OF_CONDUCT.md)。
我們希望貢獻者能遵守此約定。如果有發現任何不被接受的行為請回報至electron@github.com(PS:請用英語)。
## 下載
預編譯的二進位檔和debug symbols版可以在[releases](https://github.com/electron/electron/releases)中找到,
其中包含Linux, Windows 和 macOS版的Electron。
你也可以用[`npm`](https://docs.npmjs.com/)安裝預編譯的二進位檔:
```sh
# 在 $PATH 全域安裝 `electron`
npm install electron -g
# 安裝為開發依賴
npm install electron --save-dev
```
### 鏡像網站
- [中國](https://npm.taobao.org/mirrors/electron)
## 文件
開發指南和API文件位於
[docs](https://github.com/electron/electron/tree/master/docs)。
它也包括如何編譯看改進Electron。
## 翻譯版文件
- [葡萄牙語-巴西](https://github.com/electron/electron/tree/master/docs-translations/pt-BR)
- [韓語](https://github.com/electron/electron/tree/master/docs-translations/ko-KR)
- [日語](https://github.com/electron/electron/tree/master/docs-translations/jp)
- [西班牙語](https://github.com/electron/electron/tree/master/docs-translations/es)
- [簡體中文](https://github.com/electron/electron/tree/master/docs-translations/zh-CN)
- [正體中文](https://github.com/electron/electron/tree/master/docs-translations/zh-TW)
- [土耳其](https://github.com/electron/electron/tree/master/docs-translations/tr-TR)
- [烏克蘭](https://github.com/electron/electron/tree/master/docs-translations/uk-UA)
- [俄語](https://github.com/electron/electron/tree/master/docs-translations/ru-RU)
- [法語](https://github.com/electron/electron/tree/master/docs-translations/fr-FR)
## 快速開始
Clone 並使用 [`electron/electron-quick-start`](https://github.com/electron/electron-quick-start)
這個repo以使用輕量化的Electron。
## 社群
你可以在以下位置提問並和社群成員互動:
- [`electron`](http://discuss.atom.io/c/electron) Atom論壇上的其中一區
- `#atom-shell` Freenode的聊天頻道
- [`Atom`](http://atom-slack.herokuapp.com/) Slack上的頻道
- [`electron-br`](https://electron-br.slack.com) *(葡萄牙語-巴西)*
- [`electron-kr`](http://www.meetup.com/electron-kr/) *(韓語)*
- [`electron-jp`](https://electron-jp-slackin.herokuapp.com/) *(日語)*
- [`electron-tr`](http://www.meetup.com/Electron-JS-Istanbul/) *(土耳其)*
- [`electron-id`](https://electron-id.slack.com) *(印度尼西亞)*
在 [awesome-electron](https://github.com/sindresorhus/awesome-electron)
查看由社群維護的清單,包括實用的應用程式、工具以及資源。
## 憑證
MIT © 2016 Github

View file

@ -96,7 +96,7 @@ an issue:
* [Build Instructions (macOS)](development/build-instructions-osx.md)
* [Build Instructions (Windows)](development/build-instructions-windows.md)
* [Build Instructions (Linux)](development/build-instructions-linux.md)
* [Debug Instructions (macOS)](development/debug-instructions-macos.md)
* [Debug Instructions (macOS)](development/debugging-instructions-macos.md)
* [Debug Instructions (Windows)](development/debug-instructions-windows.md)
* [Setting Up Symbol Server in debugger](development/setting-up-symbol-server.md)
* [Documentation Styleguide](styleguide.md)

View file

@ -2,14 +2,30 @@
> Define keyboard shortcuts.
Accelerators can contain multiple modifiers and key codes, combined by
the `+` character.
Accelerators are Strings that can contain multiple modifiers and key codes,
combined by the `+` character, and are used to define keyboard shortcuts
throughout your application.
Examples:
* `CommandOrControl+A`
* `CommandOrControl+Shift+Z`
Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module
using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
method, i.e.
```javascript
const {app, globalShortcut} = require('electron')
app.on('ready', () => {
// Register a 'CommandOrControl+Y' shortcut listener.
globalShortcut.register('CommandOrControl+Y', () => {
// Do stuff when Y and either Command/Control is pressed.
})
})
```
## Platform notice
On Linux and Windows, the `Command` key does not have any effect so

View file

@ -184,15 +184,9 @@ Returns:
* `webContents` [WebContents](web-contents.md)
* `url` URL
* `error` String - The error code
* `certificate` Object
* `data` String - PEM encoded data
* `issuerName` String - Issuer's Common Name
* `subjectName` String - Subject's Common Name
* `serialNumber` String - Hex value represented string
* `validStart` Integer - Start date of the certificate being valid in seconds
* `validExpiry` Integer - End date of the certificate being valid in seconds
* `fingerprint` String - Fingerprint of the certificate
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` Boolean - Whether to consider the certificate as trusted
Emitted when failed to verify the `certificate` for `url`, to trust the
certificate you should prevent the default behavior with
@ -221,6 +215,7 @@ Returns:
* `url` URL
* `certificateList` [Certificate[]](structures/certificate.md)
* `callback` Function
* `certificate` [Certificate](structures/certificate.md)
Emitted when a client certificate is requested.
@ -255,6 +250,8 @@ Returns:
* `port` Integer
* `realm` String
* `callback` Function
* `username` String
* `password` String
Emitted when `webContents` wants to do basic auth.
@ -545,6 +542,7 @@ Returns `Boolean` - Whether the call succeeded.
### `app.getJumpListSettings()` _Windows_
Returns `Object`:
* `minItems` Integer - The minimum number of items that will be shown in the
Jump List (for a more detailed description of this value see the
[MSDN docs][JumpListBeginListMSDN]).
@ -696,6 +694,8 @@ app.setJumpList([
### `app.makeSingleInstance(callback)`
* `callback` Function
* `argv` String[] - An array of the second instance's command line arguments
* `workingDirectory` String - The second instance's working directory
This method makes your application a Single Instance Application - instead of
allowing multiple instances of your app to run, this will ensure that only a

View file

@ -185,13 +185,84 @@ It creates a new `BrowserWindow` with native properties as set by the `options`.
Default is `false`.
* `type` String - The type of window, default is normal window. See more about
this below.
* `titleBarStyle` String - The style of window title bar. See more about this
below.
* `titleBarStyle` String - The style of window title bar. Default is `default`. Possible values are:
* `default` - Results in the standard gray opaque Mac title
bar.
* `hidden` - Results in a hidden title bar and a full size content window, yet
the title bar still has the standard window controls ("traffic lights") in
the top left.
* `hidden-inset` - Results in a hidden title bar with an alternative look
where the traffic light buttons are slightly more inset from the window edge.
* `thickFrame` Boolean - Use `WS_THICKFRAME` style for frameless windows on
Windows, which adds standard window frame. Setting it to `false` will remove
window shadow and window animations. Default is `true`.
* `webPreferences` Object - Settings of web page's features. See more about
this below.
* `webPreferences` Object - Settings of web page's features.
* `devTools` Boolean - Whether to enable DevTools. If it is set to `false`, can not use `BrowserWindow.webContents.openDevTools()` to open DevTools. Default is `true`.
* `nodeIntegration` Boolean - Whether node integration is enabled. Default
is `true`.
* `preload` String - Specifies a script that will be loaded before other
scripts run in the page. This script will always have access to node APIs
no matter whether node integration is turned on or off. The value should
be the absolute file path to the script.
When node integration is turned off, the preload script can reintroduce
Node global symbols back to the global scope. See example
[here](process.md#event-loaded).
* `session` [Session](session.md#class-session) - Sets the session used by the
page. Instead of passing the Session object directly, you can also choose to
use the `partition` option instead, which accepts a partition string. When
both `session` and `partition` are provided, `session` will be preferred.
Default is the default session.
* `partition` String - Sets the session used by the page according to the
session's partition string. If `partition` starts with `persist:`, the page
will use a persistent session available to all pages in the app with the
same `partition`. If there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. Default is the default session.
* `zoomFactor` Number - The default zoom factor of the page, `3.0` represents
`300%`. Default is `1.0`.
* `javascript` Boolean - Enables JavaScript support. Default is `true`.
* `webSecurity` Boolean - When `false`, it will disable the
same-origin policy (usually using testing websites by people), and set
`allowDisplayingInsecureContent` and `allowRunningInsecureContent` to
`true` if these two options are not set by user. Default is `true`.
* `allowDisplayingInsecureContent` Boolean - Allow an https page to display
content like images from http URLs. Default is `false`.
* `allowRunningInsecureContent` Boolean - Allow an https page to run
JavaScript, CSS or plugins from http URLs. Default is `false`.
* `images` Boolean - Enables image support. Default is `true`.
* `textAreasAreResizable` Boolean - Make TextArea elements resizable. Default
is `true`.
* `webgl` Boolean - Enables WebGL support. Default is `true`.
* `webaudio` Boolean - Enables WebAudio support. Default is `true`.
* `plugins` Boolean - Whether plugins should be enabled. Default is `false`.
* `experimentalFeatures` Boolean - Enables Chromium's experimental features.
Default is `false`.
* `experimentalCanvasFeatures` Boolean - Enables Chromium's experimental
canvas features. Default is `false`.
* `scrollBounce` Boolean - Enables scroll bounce (rubber banding) effect on
macOS. Default is `false`.
* `blinkFeatures` String - A list of feature strings separated by `,`, like
`CSSVariables,KeyboardEventKey` to enable. The full list of supported feature
strings can be found in the [RuntimeEnabledFeatures.in][blink-feature-string]
file.
* `disableBlinkFeatures` String - A list of feature strings separated by `,`,
like `CSSVariables,KeyboardEventKey` to disable. The full list of supported
feature strings can be found in the
[RuntimeEnabledFeatures.in][blink-feature-string] file.
* `defaultFontFamily` Object - Sets the default font for the font-family.
* `standard` String - Defaults to `Times New Roman`.
* `serif` String - Defaults to `Times New Roman`.
* `sansSerif` String - Defaults to `Arial`.
* `monospace` String - Defaults to `Courier New`.
* `defaultFontSize` Integer - Defaults to `16`.
* `defaultMonospaceFontSize` Integer - Defaults to `13`.
* `minimumFontSize` Integer - Defaults to `0`.
* `defaultEncoding` String - Defaults to `ISO-8859-1`.
* `backgroundThrottling` Boolean - Whether to throttle animations and timers
when the page becomes background. Defaults to `true`.
* `offscreen` Boolean - Whether to enable offscreen rendering for the browser
window. Defaults to `false`.
* `sandbox` Boolean - Whether to enable Chromium OS-level sandbox.
When setting minimum or maximum window size with `minWidth`/`maxWidth`/
`minHeight`/`maxHeight`, it only constrains the users. It won't prevent you from
@ -212,85 +283,6 @@ Possible values are:
input sparingly.
* On Windows, possible type is `toolbar`.
Possible values of the `titleBarStyle` option are:
* `default` or not specified, results in the standard gray opaque Mac title
bar.
* `hidden` results in a hidden title bar and a full size content window, yet
the title bar still has the standard window controls ("traffic lights") in
the top left.
* `hidden-inset` results in a hidden title bar with an alternative look
where the traffic light buttons are slightly more inset from the window edge.
The `webPreferences` option is an object that can have the following properties:
* `devTools` Boolean - Whether to enable DevTools. If it is set to `false`, can not use `BrowserWindow.webContents.openDevTools()` to open DevTools. Default is `true`.
* `nodeIntegration` Boolean - Whether node integration is enabled. Default
is `true`.
* `preload` String - Specifies a script that will be loaded before other
scripts run in the page. This script will always have access to node APIs
no matter whether node integration is turned on or off. The value should
be the absolute file path to the script.
When node integration is turned off, the preload script can reintroduce
Node global symbols back to the global scope. See example
[here](process.md#event-loaded).
* `session` [Session](session.md#class-session) - Sets the session used by the
page. Instead of passing the Session object directly, you can also choose to
use the `partition` option instead, which accepts a partition string. When
both `session` and `partition` are provided, `session` will be preferred.
Default is the default session.
* `partition` String - Sets the session used by the page according to the
session's partition string. If `partition` starts with `persist:`, the page
will use a persistent session available to all pages in the app with the
same `partition`. If there is no `persist:` prefix, the page will use an
in-memory session. By assigning the same `partition`, multiple pages can share
the same session. Default is the default session.
* `zoomFactor` Number - The default zoom factor of the page, `3.0` represents
`300%`. Default is `1.0`.
* `javascript` Boolean - Enables JavaScript support. Default is `true`.
* `webSecurity` Boolean - When `false`, it will disable the
same-origin policy (usually using testing websites by people), and set
`allowDisplayingInsecureContent` and `allowRunningInsecureContent` to
`true` if these two options are not set by user. Default is `true`.
* `allowDisplayingInsecureContent` Boolean - Allow an https page to display
content like images from http URLs. Default is `false`.
* `allowRunningInsecureContent` Boolean - Allow an https page to run
JavaScript, CSS or plugins from http URLs. Default is `false`.
* `images` Boolean - Enables image support. Default is `true`.
* `textAreasAreResizable` Boolean - Make TextArea elements resizable. Default
is `true`.
* `webgl` Boolean - Enables WebGL support. Default is `true`.
* `webaudio` Boolean - Enables WebAudio support. Default is `true`.
* `plugins` Boolean - Whether plugins should be enabled. Default is `false`.
* `experimentalFeatures` Boolean - Enables Chromium's experimental features.
Default is `false`.
* `experimentalCanvasFeatures` Boolean - Enables Chromium's experimental
canvas features. Default is `false`.
* `scrollBounce` Boolean - Enables scroll bounce (rubber banding) effect on
macOS. Default is `false`.
* `blinkFeatures` String - A list of feature strings separated by `,`, like
`CSSVariables,KeyboardEventKey` to enable. The full list of supported feature
strings can be found in the [RuntimeEnabledFeatures.in][blink-feature-string]
file.
* `disableBlinkFeatures` String - A list of feature strings separated by `,`,
like `CSSVariables,KeyboardEventKey` to disable. The full list of supported
feature strings can be found in the
[RuntimeEnabledFeatures.in][blink-feature-string] file.
* `defaultFontFamily` Object - Sets the default font for the font-family.
* `standard` String - Defaults to `Times New Roman`.
* `serif` String - Defaults to `Times New Roman`.
* `sansSerif` String - Defaults to `Arial`.
* `monospace` String - Defaults to `Courier New`.
* `defaultFontSize` Integer - Defaults to `16`.
* `defaultMonospaceFontSize` Integer - Defaults to `13`.
* `minimumFontSize` Integer - Defaults to `0`.
* `defaultEncoding` String - Defaults to `ISO-8859-1`.
* `backgroundThrottling` Boolean - Whether to throttle animations and timers
when the page becomes background. Defaults to `true`.
* `offscreen` Boolean - Whether to enable offscreen rendering for the browser
window. Defaults to `false`.
* `sandbox` Boolean - Whether to enable Chromium OS-level sandbox.
### Instance Events
Objects created with `new BrowserWindow` emit the following events:
@ -664,6 +656,17 @@ the player itself we would call this function with arguments of 16/9 and
are within the content view--only that they exist. Just sum any extra width and
height areas you have within the overall content view.
#### `win.previewFile(path[, displayName])` _macOS_
* `path` String - The absolute path to the file to preview with QuickLook. This
is important as Quick Look uses the file name and file extension on the path
to determine the content type of the file to open.
* `displayName` String (Optional) - The name of the file to display on the
Quick Look modal view. This is purely visual and does not affect the content
type of the file. Defaults to `path`.
Uses [Quick Look][quick-look] to preview a file at a given path.
#### `win.setBounds(bounds[, animate])`
* `bounds` [Rectangle](structures/rectangle.md)
@ -950,6 +953,7 @@ Whether `Boolean` - Whether the window's document has been edited.
* `rect` [Rectangle](structures/rectangle.md) (optional) - The bounds to capture
* `callback` Function
* `image` [NativeImage](native-image.md)
Same as `webContents.capturePage([rect, ]callback)`.
@ -1113,7 +1117,7 @@ hide it immediately.
Returns `Boolean` - Whether menu bar automatically hides itself.
#### `win.setMenuBarVisibility(visible)`
#### `win.setMenuBarVisibility(visible)` _Windows_ _Linux_
* `visible` Boolean
@ -1181,3 +1185,4 @@ Returns `BrowserWindow` - The parent window.
Returns `BrowserWindow[]` - All child windows.
[window-levels]: https://developer.apple.com/reference/appkit/nswindow/1664726-window_levels
[quick-look]: https://en.wikipedia.org/wiki/Quick_Look

View file

@ -79,6 +79,7 @@ Writes the `text` into the clipboard in RTF.
### `clipboard.readBookmark()` _macOS_ _Windows_
Returns `Object`:
* `title` String
* `url` String
@ -105,6 +106,19 @@ clipboard.write({
})
```
### `clipboard.readFindText()` _macOS_
Returns `String` - The text on the find pasteboard. This method uses synchronous
IPC when called from the renderer process. The cached value is reread from the
find pasteboard whenever the application is activated.
### `clipboard.writeFindText(text)` _macOS_
* `text` String
Writes the `text` into the find pasteboard as plain text. This method uses
synchronous IPC when called from the renderer process.
### `clipboard.clear([type])`
* `type` String (optional)

View file

@ -33,6 +33,7 @@ The `contentTracing` module has the following methods:
### `contentTracing.getCategories(callback)`
* `callback` Function
* `categories` String[]
Get a set of category groups. The category groups can change as new code paths
are reached.
@ -86,6 +87,7 @@ before options parsed from `traceOptions` are applied on it.
* `resultFilePath` String
* `callback` Function
* `resultFilePath` String
Stop recording on all processes.
@ -130,6 +132,7 @@ Once all child processes have acknowledged the `stopMonitoring` request the
* `resultFilePath` String
* `callback` Function
* `resultFilePath` String
Get the current monitoring traced data.
@ -146,6 +149,8 @@ request the `callback` will be called with a file that contains the traced data.
### `contentTracing.getTraceBufferUsage(callback)`
* `callback` Function
* `value` Number
* `percentage` Number
Get the maximum usage across processes of trace buffer as a percentage of the
full state. When the TraceBufferUsage value is determined the `callback` is

View file

@ -57,6 +57,7 @@ crash reports.
### `crashReporter.getLastCrashReport()`
Returns `Object`:
* `date` String
* `ID` Integer
@ -66,6 +67,7 @@ sent or the crash reporter has not been started, `null` is returned.
### `crashReporter.getUploadedReports()`
Returns `Object[]`:
* `date` String
* `ID` Integer

View file

@ -61,25 +61,14 @@ The `desktopCapturer` module has the following methods:
* `thumbnailSize` Object (optional) - The suggested size that the media source
thumbnail should be scaled to, defaults to `{width: 150, height: 150}`.
* `callback` Function
* `error` Error
* `sources` [DesktopCapturerSource[]](structures/desktop-capturer-source.md)
Starts gathering information about all available desktop media sources,
and calls `callback(error, sources)` when finished.
`sources` is an array of `Source` objects, each `Source` represents a
screen or an individual window that can be captured, and has the following
properties:
* `id` String - The identifier of a window or screen that can be used as a
`chromeMediaSourceId` constraint when calling
[`navigator.webkitGetUserMedia`]. The format of the identifier will be
`window:XX` or `screen:XX`, where `XX` is a random generated number.
* `name` String - A screen source will be named either `Entire Screen` or
`Screen <index>`, while the name of a window source will match the window
title.
* `thumbnail` [NativeImage](native-image.md) - A thumbnail image. **Note:**
There is no guarantee that the size of the thumbnail is the same as the
`thumnbailSize` specified in the `options` passed to
`desktopCapturer.getSources`. The actual size depends on the scale of the
screen or window.
`sources` is an array of [`DesktopCapturerSource`](structures/desktop-capturer-source.md)
objects, each `DesktopCapturerSource` represents a screen or an individual window that can be
captured.
[`navigator.webkitGetUserMedia`]: https://developer.mozilla.org/en/docs/Web/API/Navigator/getUserMedia

View file

@ -34,6 +34,7 @@ The `dialog` module has the following methods:
contain `openFile`, `openDirectory`, `multiSelections`, `createDirectory`
and `showHiddenFiles`.
* `callback` Function (optional)
* `filePaths` String[] - An array of file paths chosen by the user
On success this method returns an array of file paths chosen by the user,
otherwise it returns `undefined`.
@ -74,6 +75,7 @@ shown.
left empty the default label will be used.
* `filters` String[]
* `callback` Function (optional)
* `filename` String
On success this method returns the path of the file chosen by the user,
otherwise it returns `undefined`.
@ -110,6 +112,7 @@ will be passed via `callback(filename)`
the style of modern Windows apps. If you don't like this behavior, you can
set `noLink` to `true`.
* `callback` Function
* `response` Number - The index of the button that was clicked
Shows a message box, it will block the process until the message box is closed.
It returns the index of the clicked button.

View file

@ -28,12 +28,26 @@ hidden and your content extend to the full window size, yet still preserve
the window controls ("traffic lights") for standard window actions.
You can do so by specifying the new `titleBarStyle` option:
#### `hidden`
Results in a hidden title bar and a full size content window, yet the title bar still has the standard window controls (“traffic lights”) in the top left.
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden'})
win.show()
```
#### `hidden-inset`
Results in a hidden title bar with an alternative look where the traffic light buttons are slightly more inset from the window edge.
```javascript
const {BrowserWindow} = require('electron')
let win = new BrowserWindow({titleBarStyle: 'hidden-inset'})
win.show()
```
## Transparent window
By setting the `transparent` option to `true`, you can also make the frameless

View file

@ -13,6 +13,9 @@ Create a new `MenuItem` with the following method:
* `options` Object
* `click` Function - Will be called with
`click(menuItem, browserWindow, event)` when the menu item is clicked.
* `menuItem` MenuItem
* `browserWindow` BrowserWindow
* `event` Event
* `role` String - Define the action of the menu item, when specified the
`click` property will be ignored.
* `type` String - Can be `normal`, `separator`, `submenu`, `checkbox` or

323
docs/api/net.md Normal file
View file

@ -0,0 +1,323 @@
# net
> Issue HTTP/HTTPS requests.
The `net` module is a client-side API for issuing HTTP(S) requests. It is
similar to the [HTTP](https://nodejs.org/api/http.html) and
[HTTPS](https://nodejs.org/api/https.html) modules of Node.js but uses
Chromium native networking library instead of the Node.js implementation
offering therefore a much greater support regarding web proxies.
Following is a non-exhaustive list of why you may consider using the `net`
module instead of the native Node.js modules:
* Automatic management of system proxy configuration, support of the wpad
protocol and proxy pac configuration files.
* Automatic tunneling of HTTPS requests.
* Support for authenticating proxies using basic, digest, NTLM, Kerberos or
negotiate authentication schemes.
* Support for traffic monitoring proxies: Fiddler-like proxies used for access
control and monitoring.
The `net` module API has been specifically designed to mimic, as closely as
possible, the familiar Node.js API. The API components including classes,
methods, properties and event names are similar to those commonly used in
Node.js.
For instance, the following example quickly shows how the `net` API might be
used:
```javascript
const {app} = require('electron')
app.on('ready', () => {
const {net} = require('electron')
const request = net.request('https://github.com')
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`)
console.log(`HEADERS: ${JSON.stringify(response.headers)}`)
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`)
})
response.on('end', () => {
console.log('No more data in response.')
})
})
request.end()
})
```
By the way, it is almost identical to how you would normally use the
[HTTP](https://nodejs.org/api/http.html)/[HTTPS](https://nodejs.org/api/https.html)
modules of Node.js
The `net` API can be used only after the application emits the `ready` event.
Trying to use the module before the `ready` event will throw an error.
## Methods
The `net` module has the following methods:
### `net.request(options)`
* `options`: Object or String - The `ClientRequest` constructor options.
Returns `ClientRequest`
Creates a `ClientRequest` instance using the provided `options` which are
directly forwarded to the `ClientRequest` constructor. The `net.request` method
would be used to issue both secure and insecure HTTP requests according to the
specified protocol scheme in the `options` object.
## Class: ClientRequest
`ClientRequest` implements the [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams)
interface and it is therefore an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).
### `new ClientRequest(options)`
* `options` (Object | String) - If `options` is a String, it is interpreted as
the request URL.
If it is an object, it is expected to fully specify an HTTP request via the
following properties:
* `method` String (optional) - The HTTP request method. Defaults to the GET
method.
* `url` String (optional) - The request URL. Must be provided in the absolute
form with the protocol scheme specified as http or https.
* `session` Object (optional) - The [`Session`](session.md) instance with
which the request is associated.
* `partition` String (optional) - The name of the [`partition`](session.md)
with which the request is associated. Defaults to the empty string. The
`session` option prevails on `partition`. Thus if a `session` is explicitly
specified, `partition` is ignored.
* `protocol` String (optional) - The protocol scheme in the form 'scheme:'.
Currently supported values are 'http:' or 'https:'. Defaults to 'http:'.
* `host` String (optional) - The server host provided as a concatenation of
the hostname and the port number 'hostname:port'
* `hostname` String (optional) - The server host name.
* `port` Integer (optional) - The server's listening port number.
* `path` String (optional) - The path part of the request URL.
`options` properties such as `protocol`, `host`, `hostname`, `port` and `path`
strictly follow the Node.js model as described in the
[URL](https://nodejs.org/api/url.html) module.
For instance, we could have created the same request to 'github.com' as follows:
```JavaScript
const request = net.request({
method: 'GET',
protocol: 'https:',
hostname: 'github.com',
port: 443,
path: '/'
})
```
### Instance Events
#### Event: 'response'
Returns:
* `response` IncomingMessage - An object representing the HTTP response message.
#### Event: 'login'
Returns:
* `authInfo` Object
* `isProxy` Boolean
* `scheme` String
* `host` String
* `port` Integer
* `realm` String
* `callback` Function
Emitted when an authenticating proxy is asking for user credentials.
The `callback` function is expected to be called back with user credentials:
* `username` String
* `password` String
```JavaScript
request.on('login', (authInfo, callback) => {
callback('username', 'password')
})
```
Providing empty credentials will cancel the request and report an authentication
error on the response object:
```JavaScript
request.on('response', (response) => {
console.log(`STATUS: ${response.statusCode}`);
response.on('error', (error) => {
console.log(`ERROR: ${JSON.stringify(error)}`)
})
})
request.on('login', (authInfo, callback) => {
callback()
})
```
#### Event: 'finish'
Emitted just after the last chunk of the `request`'s data has been written into
the `request` object.
#### Event: 'abort'
Emitted when the `request` is aborted. The `abort` event will not be fired if
the `request` is already closed.
#### Event: 'error'
Returns:
* `error` Error - an error object providing some information about the failure.
Emitted when the `net` module fails to issue a network request. Typically when
the `request` object emits an `error` event, a `close` event will subsequently
follow and no response object will be provided.
#### Event: 'close'
Emitted as the last event in the HTTP request-response transaction. The `close`
event indicates that no more events will be emitted on either the `request` or
`response` objects.
### Instance Properties
#### `request.chunkedEncoding`
A Boolean specifying whether the request will use HTTP chunked transfer encoding
or not. Defaults to false. The property is readable and writable, however it can
be set only before the first write operation as the HTTP headers are not yet put
on the wire. Trying to set the `chunkedEncoding` property after the first write
will throw an error.
Using chunked encoding is strongly recommended if you need to send a large
request body as data will be streamed in small chunks instead of being
internally buffered inside Electron process memory.
### Instance Methods
#### `request.setHeader(name, value)`
* `name` String - An extra HTTP header name.
* `value` String - An extra HTTP header value.
Adds an extra HTTP header. The header name will issued as it is without
lowercasing. It can be called only before first write. Calling this method after
the first write will throw an error.
#### `request.getHeader(name)`
* `name` String - Specify an extra header name.
Returns String - The value of a previously set extra header name.
#### `request.removeHeader(name)`
* `name` String - Specify an extra header name.
Removes a previously set extra header name. This method can be called only
before first write. Trying to call it after the first write will throw an error.
#### `request.write(chunk[, encoding][, callback])`
* `chunk` (String | Buffer) - A chunk of the request body's data. If it is a
string, it is converted into a Buffer using the specified encoding.
* `encoding` String (optional) - Used to convert string chunks into Buffer
objects. Defaults to 'utf-8'.
* `callback` Function (optional) - Called after the write operation ends.
`callback` is essentially a dummy function introduced in the purpose of keeping
similarity with the Node.js API. It is called asynchronously in the next tick
after `chunk` content have been delivered to the Chromium networking layer.
Contrary to the Node.js implementation, it is not guaranteed that `chunk`
content have been flushed on the wire before `callback` is called.
Adds a chunk of data to the request body. The first write operation may cause
the request headers to be issued on the wire. After the first write operation,
it is not allowed to add or remove a custom header.
#### `request.end([chunk][, encoding][, callback])`
* `chunk` (String | Buffer) (optional)
* `encoding` String (optional)
* `callback` Function (optional)
Sends the last chunk of the request data. Subsequent write or end operations
will not be allowed. The `finish` event is emitted just after the end operation.
#### `request.abort()`
Cancels an ongoing HTTP transaction. If the request has already emitted the
`close` event, the abort operation will have no effect. Otherwise an ongoing
event will emit `abort` and `close` events. Additionally, if there is an ongoing
response object,it will emit the `aborted` event.
## Class: IncomingMessage
`IncomingMessage` represents an HTTP response message.
It is a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams)
and consequently an [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).
### Instance Events
#### Event 'data'
Returns:
* `chunk`: Buffer - A chunk of response body's data.
The `data` event is the usual method of transferring response data into
applicative code.
#### Event 'end'
Indicates that response body has ended.
#### Event 'aborted'
Emitted when a request has been canceled during an ongoing HTTP transaction.
#### Event 'error'
Returns:
`error` Error - Typically holds an error string identifying failure root cause.
Emitted when an error was encountered while streaming response data events. For
instance, if the server closes the underlying while the response is still
streaming, an `error` event will be emitted on the response object and a `close`
event will subsequently follow on the request object.
### Instance properties
An `IncomingMessage` instance has the following readable properties:
#### `response.statusCode`
An Integer indicating the HTTP response status code.
#### `response.statusMessage`
A String representing the HTTP status message.
#### `response.headers`
An Object representing the response HTTP headers. The `headers` object is
formatted as follows:
* All header names are lowercased.
* Each header name produces an array-valued property on the headers object.
* Each header value is pushed into the array associated with its header name.
#### `response.httpVersion`
A String indicating the HTTP protocol version number. Typical values are '1.0'
or '1.1'. Additionally `httpVersionMajor` and `httpVersionMinor` are two
Integer-valued readable properties that return respectively the HTTP major and
minor version numbers.

View file

@ -84,6 +84,7 @@ limit, whichever is lower for the current process.
### `process.getProcessMemoryInfo()`
Returns `Object`:
* `workingSetSize` Integer - The amount of memory currently pinned to actual physical
RAM.
* `peakWorkingSetSize` Integer - The maximum amount of memory that has ever been pinned
@ -99,6 +100,7 @@ that all statistics are reported in Kilobytes.
### `process.getSystemMemoryInfo()`
Returns `Object`:
* `total` Integer - The total amount of physical memory in Kilobytes available to the
system.
* `free` Integer - The total amount of memory not being used by applications or disk

View file

@ -76,7 +76,15 @@ module gets emitted.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String (optional)
* `completion` Function (optional)
* `error` Error
Registers a protocol of `scheme` that will send the file as a response. The
`handler` will be called with `handler(request, callback)` when a `request` is
@ -84,21 +92,6 @@ going to be created with `scheme`. `completion` will be called with
`completion(null)` when `scheme` is successfully registered or
`completion(error)` when failed.
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` Array (optional)
* `callback` Function
The `uploadData` is an array of `data` objects:
* `data` Object
* `bytes` Buffer - Content being sent.
* `file` String - Path of file being uploaded.
* `blobUUID` String - UUID of blob data. Use [ses.getBlobData](session.md#sesgetblobdataidentifier-callback) method
to retrieve the data.
To handle the `request`, the `callback` should be called with either the file's
path or an object that has a `path` property, e.g. `callback(filePath)` or
`callback({path: filePath})`.
@ -117,7 +110,15 @@ treated as a standard scheme.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `buffer` Buffer (optional)
* `completion` Function (optional)
* `error` Error
Registers a protocol of `scheme` that will send a `Buffer` as a response.
@ -141,7 +142,15 @@ protocol.registerBufferProtocol('atom', (request, callback) => {
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `data` String (optional)
* `completion` Function (optional)
* `error` Error
Registers a protocol of `scheme` that will send a `String` as a response.
@ -153,7 +162,21 @@ should be called with either a `String` or an object that has the `data`,
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
* `contentType` String - MIME type of the content.
* `data` String - Content to be sent.
* `completion` Function (optional)
* `error` Error
Registers a protocol of `scheme` that will send an HTTP request as a response.
@ -161,25 +184,16 @@ The usage is the same with `registerFileProtocol`, except that the `callback`
should be called with a `redirectRequest` object that has the `url`, `method`,
`referrer`, `uploadData` and `session` properties.
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
By default the HTTP request will reuse the current session. If you want the
request to have a different session you should set `session` to `null`.
For POST requests the `uploadData` object must be provided.
* `uploadData` object
* `contentType` String - MIME type of the content.
* `data` String - Content to be sent.
### `protocol.unregisterProtocol(scheme[, completion])`
* `scheme` String
* `completion` Function (optional)
* `error` Error
Unregisters the custom protocol of `scheme`.
@ -187,6 +201,7 @@ Unregisters the custom protocol of `scheme`.
* `scheme` String
* `callback` Function
* `error` Error
The `callback` will be called with a boolean that indicates whether there is
already a handler for `scheme`.
@ -195,7 +210,15 @@ already a handler for `scheme`.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `filePath` String
* `completion` Function (optional)
* `error` Error
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a file as a response.
@ -204,7 +227,15 @@ which sends a file as a response.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `data` String (optional)
* `completion` Function (optional)
* `error` Error
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a `String` as a response.
@ -213,7 +244,15 @@ which sends a `String` as a response.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `buffer` Buffer (optional)
* `completion` Function (optional)
* `error` Error
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a `Buffer` as a response.
@ -222,7 +261,21 @@ which sends a `Buffer` as a response.
* `scheme` String
* `handler` Function
* `request` Object
* `url` String
* `referrer` String
* `method` String
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `redirectRequest` Object
* `url` String
* `method` String
* `session` Object (optional)
* `uploadData` Object (optional)
* `contentType` String - MIME type of the content.
* `data` String - Content to be sent.
* `completion` Function (optional)
* `error` Error
Intercepts `scheme` protocol and uses `handler` as the protocol's new handler
which sends a new HTTP request as a response.
@ -230,7 +283,8 @@ which sends a new HTTP request as a response.
### `protocol.uninterceptProtocol(scheme[, completion])`
* `scheme` String
* `completion` Function
* `completion` Function (optional)
* `error` Error
Remove the interceptor installed for `scheme` and restore its original handler.

View file

@ -90,6 +90,7 @@ The `screen` module has the following methods:
### `screen.getCursorScreenPoint()`
Returns `Object`:
* `x` Integer
* `y` Integer

View file

@ -200,6 +200,7 @@ The `proxyBypassRules` is a comma separated list of rules described below:
* `url` URL
* `callback` Function
* `proxy` Object
Resolves the proxy information for `url`. The `callback` will be called with
`callback(proxy)` when the request is performed.
@ -245,6 +246,10 @@ the original network configuration.
#### `ses.setCertificateVerifyProc(proc)`
* `proc` Function
* `hostname` String
* `certificate` [Certificate](structures/certificate.md)
* `callback` Function
* `isTrusted` Boolean - Determines if the certificate should be trusted
Sets the certificate verify proc for `session`, the `proc` will be called with
`proc(hostname, certificate, callback)` whenever a server certificate
@ -269,7 +274,8 @@ win.webContents.session.setCertificateVerifyProc((hostname, cert, callback) => {
* `webContents` Object - [WebContents](web-contents.md) requesting the permission.
* `permission` String - Enum of 'media', 'geolocation', 'notifications', 'midiSysex',
'pointerLock', 'fullscreen', 'openExternal'.
* `callback` Function - Allow or deny the permission.
* `callback` Function
* `permissionGranted` Boolean - Allow or deny the permission
Sets the handler which can be used to respond to permission requests for the `session`.
Calling `callback(true)` will allow the permission and `callback(false)` will reject it.
@ -402,7 +408,7 @@ The following events are available on instances of `Cookies`:
#### Event: 'changed'
* `event` Event
* `cookie` Object - The cookie that was changed
* `cookie` [Cookie](structures/cookie.md) - The cookie that was changed
* `cause` String - The cause of the change with one of the following values:
* `explicit` - The cookie was changed directly by a consumer's action.
* `overwrite` - The cookie was automatically removed due to an insert
@ -432,25 +438,13 @@ The following methods are available on instances of `Cookies`:
* `secure` Boolean (optional) - Filters cookies by their Secure property.
* `session` Boolean (optional) - Filters out session or persistent cookies.
* `callback` Function
* `error` Error
* `cookies` Cookies[]
Sends a request to get all cookies matching `details`, `callback` will be called
with `callback(error, cookies)` on complete.
`cookies` is an Array of `cookie` objects.
* `cookie` Object
* `name` String - The name of the cookie.
* `value` String - The value of the cookie.
* `domain` String - The domain of the cookie.
* `hostOnly` String - Whether the cookie is a host-only cookie.
* `path` String - The path of the cookie.
* `secure` Boolean - Whether the cookie is marked as secure.
* `httpOnly` Boolean - Whether the cookie is marked as HTTP only.
* `session` Boolean - Whether the cookie is a session cookie or a persistent
cookie with an expiration date.
* `expirationDate` Double (optional) - The expiration date of the cookie as
the number of seconds since the UNIX epoch. Not provided for session
cookies.
`cookies` is an Array of [`cookie`](structures/cookie.md) objects.
#### `cookies.set(details, callback)`
@ -468,6 +462,7 @@ with `callback(error, cookies)` on complete.
seconds since the UNIX epoch. If omitted then the cookie becomes a session
cookie and will not be retained between sessions.
* `callback` Function
* `error` Error
Sets a cookie with `details`, `callback` will be called with `callback(error)`
on complete.
@ -524,33 +519,25 @@ The following methods are available on instances of `WebRequest`:
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `uploadData` [UploadData[]](structures/upload-data.md)
* `callback` Function
* `response` Object
* `cancel` Boolean (optional)
* `redirectURL` String (optional) - The original request is prevented from
being sent or completed and is instead redirected to the given URL.
The `listener` will be called with `listener(details, callback)` when a request
is about to occur.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `uploadData` Array (optional)
* `callback` Function
The `uploadData` is an array of `UploadData` objects.
The `uploadData` is an array of `data` objects:
* `data` Object
* `bytes` Buffer - Content being sent.
* `file` String - Path of file being uploaded.
* `blobUUID` String - UUID of blob data. Use [ses.getBlobData](session.md#sesgetblobdataidentifier-callback) method
to retrieve the data.
The `callback` has to be called with an `response` object:
* `response` Object
* `cancel` Boolean (optional)
* `redirectURL` String (optional) - The original request is prevented from
being sent or completed, and is instead redirected to the given URL.
The `callback` has to be called with an `response` object.
#### `webRequest.onBeforeSendHeaders([filter, ]listener)`
@ -569,31 +556,29 @@ TCP connection is made to the server, but before any http data is sent.
* `timestamp` Double
* `requestHeaders` Object
* `callback` Function
* `response` Object
* `cancel` Boolean (optional)
* `requestHeaders` Object (optional) - When provided, request will be made
with these headers.
The `callback` has to be called with an `response` object:
* `response` Object
* `cancel` Boolean (optional)
* `requestHeaders` Object (optional) - When provided, request will be made
with these headers.
The `callback` has to be called with an `response` object.
#### `webRequest.onSendHeaders([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `requestHeaders` Object
The `listener` will be called with `listener(details)` just before a request is
going to be sent to the server, modifications of previous `onBeforeSendHeaders`
response are visible by the time this listener is fired.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `requestHeaders` Object
#### `webRequest.onHeadersReceived([filter, ]listener)`
* `filter` Object
@ -612,90 +597,85 @@ response headers of a request have been received.
* `statusCode` Integer
* `responseHeaders` Object
* `callback` Function
* `response` Object
* `cancel` Boolean
* `responseHeaders` Object (optional) - When provided, the server is assumed
to have responded with these headers.
* `statusLine` String (optional) - Should be provided when overriding
`responseHeaders` to change header status otherwise original response
header's status will be used.
The `callback` has to be called with an `response` object:
* `response` Object
* `cancel` Boolean
* `responseHeaders` Object (optional) - When provided, the server is assumed
to have responded with these headers.
* `statusLine` String (optional) - Should be provided when overriding
`responseHeaders` to change header status otherwise original response
header's status will be used.
The `callback` has to be called with an `response` object.
#### `webRequest.onResponseStarted([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean - Indicates whether the response was fetched from disk
cache.
* `statusCode` Integer
* `statusLine` String
The `listener` will be called with `listener(details)` when first byte of the
response body is received. For HTTP requests, this means that the status line
and response headers are available.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean - Indicates whether the response was fetched from disk
cache.
* `statusCode` Integer
* `statusLine` String
#### `webRequest.onBeforeRedirect([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` String
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `redirectURL` String
* `statusCode` Integer
* `ip` String (optional) - The server IP address that the request was
actually sent to.
* `fromCache` Boolean
* `responseHeaders` Object
The `listener` will be called with `listener(details)` when a server initiated
redirect is about to occur.
* `details` Object
* `id` String
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `redirectURL` String
* `statusCode` Integer
* `ip` String (optional) - The server IP address that the request was
actually sent to.
* `fromCache` Boolean
* `responseHeaders` Object
#### `webRequest.onCompleted([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean
* `statusCode` Integer
* `statusLine` String
The `listener` will be called with `listener(details)` when a request is
completed.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `responseHeaders` Object
* `fromCache` Boolean
* `statusCode` Integer
* `statusLine` String
#### `webRequest.onErrorOccurred([filter, ]listener)`
* `filter` Object
* `listener` Function
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `fromCache` Boolean
* `error` String - The error description.
The `listener` will be called with `listener(details)` when an error occurs.
* `details` Object
* `id` Integer
* `url` String
* `method` String
* `resourceType` String
* `timestamp` Double
* `fromCache` Boolean
* `error` String - The error description.

View file

@ -0,0 +1,4 @@
# BluetoothDevice Object
* `deviceName` String
* `deviceId` String

View file

@ -0,0 +1,14 @@
# Cookie Object
* `name` String - The name of the cookie.
* `value` String - The value of the cookie.
* `domain` String - The domain of the cookie.
* `hostOnly` String - Whether the cookie is a host-only cookie.
* `path` String - The path of the cookie.
* `secure` Boolean - Whether the cookie is marked as secure.
* `httpOnly` Boolean - Whether the cookie is marked as HTTP only.
* `session` Boolean - Whether the cookie is a session cookie or a persistent
cookie with an expiration date.
* `expirationDate` Double (optional) - The expiration date of the cookie as
the number of seconds since the UNIX epoch. Not provided for session
cookies.

View file

@ -0,0 +1,14 @@
# DesktopCapturerSource Object
* `id` String - The identifier of a window or screen that can be used as a
`chromeMediaSourceId` constraint when calling
[`navigator.webkitGetUserMedia`]. The format of the identifier will be
`window:XX` or `screen:XX`, where `XX` is a random generated number.
* `name` String - A screen source will be named either `Entire Screen` or
`Screen <index>`, while the name of a window source will match the window
title.
* `thumbnail` [NativeImage](../native-image.md) - A thumbnail image. **Note:**
There is no guarantee that the size of the thumbnail is the same as the
`thumbnailSize` specified in the `options` passed to
`desktopCapturer.getSources`. The actual size depends on the scale of the
screen or window.

View file

@ -0,0 +1,6 @@
# UploadData Object
* `bytes` Buffer - Content being sent.
* `file` String - Path of file being uploaded.
* `blobUUID` String - UUID of blob data. Use [ses.getBlobData](../session.md#sesgetblobdataidentifier-callback) method
to retrieve the data.

View file

@ -63,6 +63,8 @@ that contains the user information dictionary sent along with the notification.
* `event` String
* `callback` Function
* `event` String
* `userInfo` Object
Subscribes to native notifications of macOS, `callback` will be called with
`callback(event, userInfo)` when the corresponding `event` happens. The
@ -90,6 +92,8 @@ Removes the subscriber with `id`.
* `event` String
* `callback` Function
* `event` String
* `userInfo` Object
Same as `subscribeNotification`, but uses `NSNotificationCenter` for local defaults.
This is necessary for events such as `NSUserDefaultsDidChangeNotification`

Some files were not shown because too many files have changed in this diff Show more