Merge pull request #3 from atom/master

Update from original
This commit is contained in:
Eran Tiktin 2015-09-16 18:03:20 +03:00
commit 25a2f28501
175 changed files with 2577 additions and 1212 deletions

View file

@ -29,6 +29,7 @@ possible with your report. If you can, please include:
* Include screenshots and animated GIFs in your pull request whenever possible.
* Follow the CoffeeScript, JavaScript, C++ and Python [coding style defined in docs](/docs/development/coding-style.md).
* Write documentation in [Markdown](https://daringfireball.net/projects/markdown).
See the [Documentation Styleguide](/docs/styleguide.md).
* Use short, present tense commit messages. See [Commit Message Styleguide](#git-commit-messages-styleguide).
## Styleguides

View file

@ -6,13 +6,15 @@
### [Electron](https://github.com/atom/electron/) 한국어 참조문서
:zap: *프레임워크 이름이 Atom Shell에서 Electron으로 바뀌었습니다* :zap:
:zap: *프레임워크 이름이 Atom Shell에서 Electron으로 변경되었습니다* :zap:
Electron 프레임워크는 JavaScript, HTML 그리고 CSS를 사용하여 Cross-Platform 데스크톱 어플리케이션을 개발할 수 있도록 해주는 프레임워크입니다. 이 프레임워크는 [io.js](http://iojs.org) 와
[Chromium](http://www.chromium.org)을 기반으로 만들어 졌으며 [Atom Editor](https://github.com/atom/atom)에 사용되고 있습니다.
Electron에 대한 중요한 알림을 받고 싶다면 Twitter에서 [@ElectronJS](https://twitter.com/electronjs)를 팔로우 하세요.
이 프로젝트는 기여자 규약 1.2를 준수합니다. 이 프로젝트에 참여할 때 코드를 유지해야 합니다. 받아들일 수 없는 행동은 atom@github.com로 보고 하십시오.
## 다운로드
Linux, Windows, Mac용으로 미리 빌드된 Electron 바이너리와 디버그 심볼이 준비되어 있습니다. [releases](https://github.com/atom/electron/releases) 페이지에서 받아 볼 수 있습니다.
@ -38,12 +40,19 @@ Electron을 빌드 하는 방법과 프로젝트에 기여하는 방법도 문
## 참조 문서 (번역)
- [브라질 포르투칼어](https://github.com/atom/electron/tree/master/docs-translations/pt-BR)
- [한국어](https://github.com/atom/electron/tree/master/docs-translations/ko)
- [일본어](https://github.com/atom/electron/tree/master/docs-translations/jp)
- [스페인어](https://github.com/atom/electron/tree/master/docs-translations/es)
- [중국어 간체](https://github.com/atom/electron/tree/master/docs-translations/zh-CN)
- [중국어 번체](https://github.com/atom/electron/tree/master/docs-translations/zh-TW)
## 커뮤니티
[Atom 포럼내의 `electron` 카테고리](http://discuss.atom.io/category/electron)와 Freenode `#atom-shell` 채팅 채널에서 활발하게 토론이 이어지고 있습니다.
다음 링크를 통해 커뮤니티에 질문을 올리거나 토론을 나누실 수 있습니다:
- Atom 포럼의 [`electron`](http://discuss.atom.io/category/electron) 카테고리
- Freenode 채팅의 `#atom-shell` 채널
- Slack의 [`Atom`](http://atom-slack.herokuapp.com/) 채널
[awesome-electron](https://github.com/sindresorhus/awesome-electron) 프로젝트엔 커뮤니티가 운영중인 유용한 예제 어플리케이션과 도구, 리소스가 있으니 한번 참고해 보시기 바랍니다.

View file

@ -4,7 +4,7 @@
[![devDependency Status](https://david-dm.org/atom/electron/dev-status.svg)](https://david-dm.org/atom/electron#info=devDependencies)
[![Join the Electron Community on Slack](http://atom-slack.herokuapp.com/badge.svg)](http://atom-slack.herokuapp.com/)
:zap: *formerly known as Atom Shell* :zap:
:zap: *Formerly known as Atom Shell* :zap:
The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [io.js](http://iojs.org) and
@ -15,7 +15,8 @@ Follow [@ElectronJS](https://twitter.com/electronjs) on Twitter for important
announcements.
This project adheres to the [Contributor Covenant 1.2](http://contributor-covenant.org/version/1/2/0).
By participating, you are expected to uphold this code. Please report unacceptable behavior to atom@github.com.
By participating, you are expected to uphold this code. Please report
unacceptable behavior to atom@github.com.
## Downloads
@ -45,6 +46,7 @@ contains documents describing how to build and contribute to Electron.
## Documentation Translations
- [Brazilian Portuguese](https://github.com/atom/electron/tree/master/docs-translations/pt-BR)
- [Korean](https://github.com/atom/electron/tree/master/docs-translations/ko)
- [Japanese](https://github.com/atom/electron/tree/master/docs-translations/jp)
- [Spanish](https://github.com/atom/electron/tree/master/docs-translations/es)
@ -53,7 +55,12 @@ contains documents describing how to build and contribute to Electron.
## Community
There is an [`electron` category on the Atom forums](http://discuss.atom.io/category/electron)
as well as an `#atom-shell` channel on Freenode.
You can ask questions and interact with the community in the following
locations:
- [`electron`](http://discuss.atom.io/category/electron) category on the Atom
forums
- `#atom-shell` channel on Freenode
- [`Atom`](http://atom-slack.herokuapp.com/) channel on Slack
Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron) for a community maintained list of useful example apps, tools and resources.
Check out [awesome-electron](https://github.com/sindresorhus/awesome-electron)
for a community maintained list of useful example apps, tools and resources.

View file

@ -4,7 +4,7 @@
'product_name%': 'Electron',
'company_name%': 'GitHub, Inc',
'company_abbr%': 'github',
'version%': '0.31.2',
'version%': '0.32.3',
},
'includes': [
'filenames.gypi',

View file

@ -7,6 +7,7 @@
#include <string>
#include <vector>
#include "atom/common/atom_version.h"
#include "atom/common/chrome_version.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
@ -14,6 +15,7 @@
#include "base/strings/string_util.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/pepper_plugin_info.h"
#include "content/public/common/user_agent.h"
#include "ppapi/shared_impl/ppapi_permissions.h"
namespace atom {
@ -72,6 +74,12 @@ std::string AtomContentClient::GetProduct() const {
return "Chrome/" CHROME_VERSION_STRING;
}
std::string AtomContentClient::GetUserAgent() const {
return content::BuildUserAgentFromProduct(
"Chrome/" CHROME_VERSION_STRING " "
ATOM_PRODUCT_NAME "/" ATOM_VERSION_STRING);
}
void AtomContentClient::AddAdditionalSchemes(
std::vector<std::string>* standard_schemes,
std::vector<std::string>* savable_schemes) {

View file

@ -20,6 +20,7 @@ class AtomContentClient : public brightray::ContentClient {
protected:
// content::ContentClient:
std::string GetProduct() const override;
std::string GetUserAgent() const override;
void AddAdditionalSchemes(
std::vector<std::string>* standard_schemes,
std::vector<std::string>* savable_schemes) override;

View file

@ -38,7 +38,9 @@ bool AtomMainDelegate::BasicStartupComplete(int* exit_code) {
#else
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif // defined(DEBUG)
#endif // defined(OS_WIN)
#else // defined(OS_WIN)
settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif // !defined(OS_WIN)
logging::InitLogging(settings);
// Logging with pid and timestamp.

View file

@ -19,6 +19,7 @@
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/files/file_path.h"
@ -34,8 +35,6 @@
#include "base/strings/utf_string_conversions.h"
#endif
#include "atom/common/node_includes.h"
using atom::Browser;
namespace mate {
@ -168,8 +167,8 @@ void App::OnOpenURL(const std::string& url) {
Emit("open-url", url);
}
void App::OnActivateWithNoOpenWindows() {
Emit("activate-with-no-open-windows");
void App::OnActivate(bool has_visible_windows) {
Emit("activate", has_visible_windows);
}
void App::OnWillFinishLaunching() {

View file

@ -41,7 +41,7 @@ class App : public mate::EventEmitter,
void OnQuit() override;
void OnOpenFile(bool* prevent_default, const std::string& file_path) override;
void OnOpenURL(const std::string& url) override;
void OnActivateWithNoOpenWindows() override;
void OnActivate(bool has_visible_windows) override;
void OnWillFinishLaunching() override;
void OnFinishLaunching() override;
void OnSelectCertificate(

View file

@ -7,11 +7,10 @@
#include "base/time/time.h"
#include "atom/browser/auto_updater.h"
#include "atom/browser/browser.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {

View file

@ -7,13 +7,12 @@
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "content/public/browser/tracing_controller.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
using content::TracingController;
namespace mate {

View file

@ -20,8 +20,6 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "atom/common/node_includes.h"
using atom::api::Cookies;
using content::BrowserThread;

View file

@ -78,7 +78,7 @@ class Cookies : public mate::Wrappable {
// Must be called on IO thread.
net::CookieStore* GetCookieStore();
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
DISALLOW_COPY_AND_ASSIGN(Cookies);
};

View file

@ -5,12 +5,11 @@
#include "atom/browser/api/atom_api_power_monitor.h"
#include "atom/browser/browser.h"
#include "atom/common/node_includes.h"
#include "base/power_monitor/power_monitor.h"
#include "base/power_monitor/power_monitor_device_source.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
@ -41,9 +40,9 @@ void PowerMonitor::OnResume() {
// static
v8::Local<v8::Value> PowerMonitor::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate,
"Cannot initialize \"power-monitor\" module before app is ready");
"Cannot initialize \"power-monitor\" module before app is ready")));
return v8::Null(isolate);
}

View file

@ -6,9 +6,9 @@
#include <string>
#include "atom/common/node_includes.h"
#include "content/public/browser/power_save_blocker.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
namespace mate {

View file

@ -12,9 +12,8 @@
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
using content::BrowserThread;

View file

@ -66,7 +66,7 @@ class Protocol : public mate::Wrappable {
public:
CustomProtocolHandler(
v8::Isolate* isolate,
scoped_refptr<net::URLRequestContextGetter> request_context,
net::URLRequestContextGetter* request_context,
const Handler& handler)
: isolate_(isolate),
request_context_(request_context),
@ -83,7 +83,7 @@ class Protocol : public mate::Wrappable {
private:
v8::Isolate* isolate_;
scoped_refptr<net::URLRequestContextGetter> request_context_;
net::URLRequestContextGetter* request_context_;
Protocol::Handler handler_;
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
@ -172,7 +172,7 @@ class Protocol : public mate::Wrappable {
// Convert error code to string.
std::string ErrorCodeToString(ProtocolError error);
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
// Map that stores the original protocols of schemes.
using OriginalProtocolsMap = base::ScopedPtrHashMap<

View file

@ -113,14 +113,16 @@ mate::ObjectTemplateBuilder Screen::GetObjectTemplateBuilder(
// static
v8::Local<v8::Value> Screen::Create(v8::Isolate* isolate) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate,
"Cannot initialize \"screen\" module before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate,
"Cannot initialize \"screen\" module before app is ready")));
return v8::Null(isolate);
}
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
if (!screen) {
node::ThrowError(isolate, "Failed to get screen information");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Failed to get screen information")));
return v8::Null(isolate);
}

View file

@ -13,6 +13,7 @@
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/files/file_path.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
@ -29,8 +30,6 @@
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
using content::StoragePartition;
@ -233,16 +232,16 @@ void SetProxyInIO(net::URLRequestContextGetter* getter,
Session::Session(AtomBrowserContext* browser_context)
: browser_context_(browser_context) {
AttachAsUserData(browser_context);
// Observe DownloadManger to get download notifications.
auto download_manager =
content::BrowserContext::GetDownloadManager(browser_context);
download_manager->AddObserver(this);
content::BrowserContext::GetDownloadManager(browser_context)->
AddObserver(this);
}
Session::~Session() {
auto download_manager =
content::BrowserContext::GetDownloadManager(browser_context_);
download_manager->RemoveObserver(this);
content::BrowserContext::GetDownloadManager(browser_context())->
RemoveObserver(this);
Destroy();
}
void Session::OnDownloadCreated(content::DownloadManager* manager,
@ -257,8 +256,16 @@ void Session::OnDownloadCreated(content::DownloadManager* manager,
}
}
bool Session::IsDestroyed() const {
return !browser_context_;
}
void Session::Destroy() {
browser_context_ = nullptr;
}
void Session::ResolveProxy(const GURL& url, ResolveProxyCallback callback) {
new ResolveProxyHelper(browser_context_, url, callback);
new ResolveProxyHelper(browser_context(), url, callback);
}
void Session::ClearCache(const net::CompletionCallback& callback) {
@ -279,7 +286,7 @@ void Session::ClearStorageData(mate::Arguments* args) {
}
auto storage_partition =
content::BrowserContext::GetStoragePartition(browser_context_, nullptr);
content::BrowserContext::GetStoragePartition(browser_context(), nullptr);
storage_partition->ClearData(
options.storage_types, options.quota_types, options.origin,
content::StoragePartition::OriginMatcherFunction(),
@ -300,7 +307,7 @@ void Session::SetDownloadPath(const base::FilePath& path) {
v8::Local<v8::Value> Session::Cookies(v8::Isolate* isolate) {
if (cookies_.IsEmpty()) {
auto handle = atom::api::Cookies::Create(isolate, browser_context_);
auto handle = atom::api::Cookies::Create(isolate, browser_context());
cookies_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, cookies_);
@ -319,8 +326,7 @@ mate::ObjectTemplateBuilder Session::GetObjectTemplateBuilder(
// static
mate::Handle<Session> Session::CreateFrom(
v8::Isolate* isolate,
AtomBrowserContext* browser_context) {
v8::Isolate* isolate, AtomBrowserContext* browser_context) {
auto existing = TrackableObject::FromWrappedClass(isolate, browser_context);
if (existing)
return mate::CreateHandle(isolate, static_cast<Session*>(existing));
@ -330,6 +336,14 @@ mate::Handle<Session> Session::CreateFrom(
return handle;
}
// static
mate::Handle<Session> Session::FromPartition(
v8::Isolate* isolate, const std::string& partition, bool in_memory) {
auto browser_context = brightray::BrowserContext::From(partition, in_memory);
return CreateFrom(isolate,
static_cast<AtomBrowserContext*>(browser_context.get()));
}
void SetWrapSession(const WrapSessionCallback& callback) {
g_wrap_session = callback;
}
@ -348,6 +362,7 @@ void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("fromPartition", &atom::api::Session::FromPartition);
dict.SetMethod("_setWrapSession", &atom::api::SetWrapSession);
dict.SetMethod("_clearWrapSession", &atom::api::ClearWrapSession);
}

View file

@ -37,7 +37,11 @@ class Session: public mate::TrackableObject<Session>,
static mate::Handle<Session> CreateFrom(
v8::Isolate* isolate, AtomBrowserContext* browser_context);
AtomBrowserContext* browser_context() const { return browser_context_; }
// Gets the Session of |partition| and |in_memory|.
static mate::Handle<Session> FromPartition(
v8::Isolate* isolate, const std::string& partition, bool in_memory);
AtomBrowserContext* browser_context() const { return browser_context_.get(); }
protected:
explicit Session(AtomBrowserContext* browser_context);
@ -47,11 +51,15 @@ class Session: public mate::TrackableObject<Session>,
void OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* item) override;
// mate::Wrappable implementations:
// mate::Wrappable:
mate::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
bool IsDestroyed() const override;
private:
// mate::TrackableObject:
void Destroy() override;
void ResolveProxy(const GURL& url, ResolveProxyCallback callback);
void ClearCache(const net::CompletionCallback& callback);
void ClearStorageData(mate::Arguments* args);
@ -59,9 +67,10 @@ class Session: public mate::TrackableObject<Session>,
void SetDownloadPath(const base::FilePath& path);
v8::Local<v8::Value> Cookies(v8::Isolate* isolate);
// Cached object for cookies API.
v8::Global<v8::Value> cookies_;
AtomBrowserContext* browser_context_; // weak ref
scoped_refptr<AtomBrowserContext> browser_context_;
DISALLOW_COPY_AND_ASSIGN(Session);
};

View file

@ -12,13 +12,12 @@
#include "atom/common/native_mate_converters/gfx_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
#include "ui/events/event_constants.h"
#include "ui/gfx/image/image.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace api {
@ -35,7 +34,8 @@ Tray::~Tray() {
// static
mate::Wrappable* Tray::New(v8::Isolate* isolate, const gfx::Image& image) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate, "Cannot create Tray before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create Tray before app is ready")));
return nullptr;
}
return new Tray(image);

View file

@ -11,6 +11,7 @@
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/native_window.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/web_view_guest_delegate.h"
#include "atom/common/api/api_messages.h"
#include "atom/common/api/event_emitter_caller.h"
@ -153,31 +154,41 @@ WebContents::WebContents(content::WebContents* web_contents)
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
}
WebContents::WebContents(const mate::Dictionary& options) {
WebContents::WebContents(v8::Isolate* isolate,
const mate::Dictionary& options) {
// Whether it is a guest WebContents.
bool is_guest = false;
options.Get("isGuest", &is_guest);
type_ = is_guest ? WEB_VIEW : BROWSER_WINDOW;
content::BrowserContext* browser_context =
AtomBrowserMainParts::Get()->browser_context();
// Obtain the session.
std::string partition;
mate::Handle<api::Session> session;
if (options.Get("session", &session)) {
} else if (options.Get("partition", &partition) && !partition.empty()) {
bool in_memory = true;
if (base::StartsWith(partition, "persist:", base::CompareCase::SENSITIVE)) {
in_memory = false;
partition = partition.substr(8);
}
session = Session::FromPartition(isolate, partition, in_memory);
} else {
// Use the default session if not specified.
session = Session::FromPartition(isolate, "", false);
}
session_.Reset(isolate, session.ToV8());
content::WebContents* web_contents;
if (is_guest) {
GURL guest_site;
options.Get("partition", &guest_site);
// use hosts' browser_context when no partition is specified.
if (!guest_site.query().empty()) {
browser_context = AtomBrowserMainParts::Get()
->GetBrowserContextForPartition(guest_site);
}
auto site_instance =
content::SiteInstance::CreateForURL(browser_context, guest_site);
content::WebContents::CreateParams params(browser_context, site_instance);
content::SiteInstance* site_instance = content::SiteInstance::CreateForURL(
session->browser_context(), GURL("chrome-guest://fake-host"));
content::WebContents::CreateParams params(
session->browser_context(), site_instance);
guest_delegate_.reset(new WebViewGuestDelegate);
params.guest_delegate = guest_delegate_.get();
web_contents = content::WebContents::Create(params);
} else {
content::WebContents::CreateParams params(browser_context);
content::WebContents::CreateParams params(session->browser_context());
web_contents = content::WebContents::Create(params);
}
@ -185,6 +196,11 @@ WebContents::WebContents(const mate::Dictionary& options) {
AttachAsUserData(web_contents);
InitWithWebContents(web_contents);
// Save the preferences.
base::DictionaryValue web_preferences;
mate::ConvertFromV8(isolate, options.GetHandle(), &web_preferences);
new WebContentsPreferences(web_contents, &web_preferences);
web_contents->SetUserAgentOverride(GetBrowserContext()->GetUserAgent());
if (is_guest) {
@ -372,7 +388,7 @@ void WebContents::DidFailProvisionalLoad(
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
Emit("did-fail-load", error_code, error_description);
Emit("did-fail-load", error_code, error_description, validated_url);
}
void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
@ -380,7 +396,7 @@ void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host,
int error_code,
const base::string16& error_description,
bool was_ignored_by_handler) {
Emit("did-fail-load", error_code, error_description);
Emit("did-fail-load", error_code, error_description, validated_url);
}
void WebContents::DidStartLoading() {
@ -489,6 +505,7 @@ void WebContents::NavigationEntryCommitted(
}
void WebContents::Destroy() {
session_.Reset();
if (type_ == WEB_VIEW && managed_web_contents()) {
// When force destroying the "destroyed" event is not emitted.
WebContentsDestroyed();
@ -530,6 +547,10 @@ void WebContents::LoadURL(const GURL& url, const mate::Dictionary& options) {
web_contents()->GetController().LoadURLWithParams(params);
}
GURL WebContents::GetURL() const {
return web_contents()->GetURL();
}
base::string16 WebContents::GetTitle() const {
return web_contents()->GetTitle();
}
@ -651,10 +672,6 @@ void WebContents::InspectServiceWorker() {
}
v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) {
if (session_.IsEmpty()) {
auto handle = Session::CreateFrom(isolate, GetBrowserContext());
session_.Reset(isolate, handle.ToV8());
}
return v8::Local<v8::Value>::New(isolate, session_);
}
@ -704,17 +721,19 @@ void WebContents::PrintToPDF(const base::DictionaryValue& setting,
PrintToPDF(setting, callback);
}
void WebContents::AddWorkSpace(const base::FilePath& path) {
void WebContents::AddWorkSpace(mate::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
node::ThrowError(isolate(), "path cannot be empty");
args->ThrowError("path cannot be empty");
return;
}
DevToolsAddFileSystem(path);
}
void WebContents::RemoveWorkSpace(const base::FilePath& path) {
void WebContents::RemoveWorkSpace(mate::Arguments* args,
const base::FilePath& path) {
if (path.empty()) {
node::ThrowError(isolate(), "path cannot be empty");
args->ThrowError("path cannot be empty");
return;
}
DevToolsRemoveFileSystem(path);
@ -800,6 +819,7 @@ mate::ObjectTemplateBuilder WebContents::GetObjectTemplateBuilder(
.SetMethod("getId", &WebContents::GetID)
.SetMethod("equal", &WebContents::Equal)
.SetMethod("_loadUrl", &WebContents::LoadURL)
.SetMethod("_getUrl", &WebContents::GetURL)
.SetMethod("getTitle", &WebContents::GetTitle)
.SetMethod("isLoading", &WebContents::IsLoading)
.SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse)
@ -890,7 +910,7 @@ mate::Handle<WebContents> WebContents::CreateFrom(
// static
mate::Handle<WebContents> WebContents::Create(
v8::Isolate* isolate, const mate::Dictionary& options) {
auto handle = mate::CreateHandle(isolate, new WebContents(options));
auto handle = mate::CreateHandle(isolate, new WebContents(isolate, options));
g_wrap_web_contents.Run(handle.ToV8());
return handle;
}

View file

@ -48,11 +48,14 @@ class WebContents : public mate::TrackableObject<WebContents>,
static mate::Handle<WebContents> Create(
v8::Isolate* isolate, const mate::Dictionary& options);
void Destroy();
// mate::TrackableObject:
void Destroy() override;
bool IsAlive() const;
int GetID() const;
bool Equal(const WebContents* web_contents) const;
void LoadURL(const GURL& url, const mate::Dictionary& options);
GURL GetURL() const;
base::string16 GetTitle() const;
bool IsLoading() const;
bool IsWaitingForResponse() const;
@ -85,8 +88,8 @@ class WebContents : public mate::TrackableObject<WebContents>,
const PrintToPDFCallback& callback);
// DevTools workspace api.
void AddWorkSpace(const base::FilePath& path);
void RemoveWorkSpace(const base::FilePath& path);
void AddWorkSpace(mate::Arguments* args, const base::FilePath& path);
void RemoveWorkSpace(mate::Arguments* args, const base::FilePath& path);
// Editing commands.
void Undo();
@ -116,7 +119,7 @@ class WebContents : public mate::TrackableObject<WebContents>,
protected:
explicit WebContents(content::WebContents* web_contents);
explicit WebContents(const mate::Dictionary& options);
WebContents(v8::Isolate* isolate, const mate::Dictionary& options);
~WebContents();
// mate::Wrappable:

View file

@ -3,14 +3,14 @@
// found in the LICENSE file.
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_view_constants.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/web_view_manager.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/browser/browser_context.h"
#include "native_mate/dictionary.h"
#include "net/base/filename_util.h"
#include "atom/common/node_includes.h"
using atom::WebContentsPreferences;
namespace mate {
@ -26,31 +26,6 @@ struct Converter<content::WebContents*> {
}
};
template<>
struct Converter<atom::WebViewManager::WebViewInfo> {
static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
atom::WebViewManager::WebViewInfo* out) {
Dictionary options;
if (!ConvertFromV8(isolate, val, &options))
return false;
GURL preload_url;
if (!options.Get(atom::web_view::kPreloadUrl, &preload_url))
return false;
if (!preload_url.is_empty() &&
!net::FileURLToFilePath(preload_url, &(out->preload_script)))
return false;
return options.Get(atom::web_view::kNodeIntegration,
&(out->node_integration)) &&
options.Get(atom::web_view::kPlugins, &(out->plugins)) &&
options.Get(atom::web_view::kPartitionId, &(out->partition_id)) &&
options.Get(atom::web_view::kDisableWebSecurity,
&(out->disable_web_security));
}
};
} // namespace mate
namespace {
@ -69,17 +44,13 @@ void AddGuest(int guest_instance_id,
int element_instance_id,
content::WebContents* embedder,
content::WebContents* guest_web_contents,
atom::WebViewManager::WebViewInfo info) {
const base::DictionaryValue& options) {
auto manager = GetWebViewManager(embedder);
if (manager)
manager->AddGuest(guest_instance_id, element_instance_id, embedder,
guest_web_contents);
info.guest_instance_id = guest_instance_id;
info.embedder = embedder;
auto data = new atom::WebViewManager::WebViewInfoUserData(info);
guest_web_contents->SetUserData(
atom::web_view::kWebViewInfoKeyName, data);
WebContentsPreferences::FromWebContents(guest_web_contents)->Merge(options);
}
void RemoveGuest(content::WebContents* embedder, int guest_instance_id) {

View file

@ -13,6 +13,7 @@
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/options_switches.h"
#include "content/public/browser/render_process_host.h"
#include "native_mate/constructor.h"
#include "native_mate/dictionary.h"
@ -64,9 +65,21 @@ void OnCapturePageDone(
Window::Window(v8::Isolate* isolate, const mate::Dictionary& options) {
// Use options['web-preferences'] to create WebContents.
mate::Dictionary web_preferences = mate::Dictionary::CreateEmpty(isolate);
options.Get(switches::kWebPreferences, &web_preferences);
// Be compatible with old options which are now in web_preferences.
v8::Local<v8::Value> value;
if (options.Get(switches::kNodeIntegration, &value))
web_preferences.Set(switches::kNodeIntegration, value);
if (options.Get(switches::kPreloadScript, &value))
web_preferences.Set(switches::kPreloadScript, value);
if (options.Get(switches::kZoomFactor, &value))
web_preferences.Set(switches::kZoomFactor, value);
// Creates the WebContents used by BrowserWindow.
mate::Dictionary web_contents_options(isolate, v8::Object::New(isolate));
auto web_contents = WebContents::Create(isolate, web_contents_options);
auto web_contents = WebContents::Create(isolate, web_preferences);
web_contents_.Reset(isolate, web_contents.ToV8());
api_web_contents_ = web_contents.get();
@ -170,21 +183,21 @@ void Window::OnDevToolsFocus() {
}
void Window::OnDevToolsOpened() {
Emit("devtools-opened");
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
auto handle = WebContents::CreateFrom(
isolate(), api_web_contents_->GetDevToolsWebContents());
devtools_web_contents_.Reset(isolate(), handle.ToV8());
Emit("devtools-opened");
}
void Window::OnDevToolsClosed() {
Emit("devtools-closed");
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
devtools_web_contents_.Reset();
Emit("devtools-closed");
}
void Window::OnExecuteWindowsCommand(const std::string& command_name) {
@ -195,8 +208,8 @@ void Window::OnExecuteWindowsCommand(const std::string& command_name) {
mate::Wrappable* Window::New(v8::Isolate* isolate,
const mate::Dictionary& options) {
if (!Browser::Get()->is_ready()) {
node::ThrowError(isolate,
"Cannot create BrowserWindow before app is ready");
isolate->ThrowException(v8::Exception::Error(mate::StringToV8(
isolate, "Cannot create BrowserWindow before app is ready")));
return nullptr;
}
return new Window(isolate, options);
@ -207,7 +220,10 @@ bool Window::IsDestroyed() const {
}
void Window::Destroy() {
window_->CloseContents(nullptr);
if (window_) {
window_->CloseContents(nullptr);
window_.reset();
}
}
void Window::Close() {
@ -398,6 +414,10 @@ bool Window::IsWebViewFocused() {
return window_->IsWebViewFocused();
}
bool Window::IsDevToolsFocused() {
return window_->IsDevToolsFocused();
}
void Window::SetRepresentedFilename(const std::string& filename) {
window_->SetRepresentedFilename(filename);
}
@ -575,6 +595,7 @@ void Window::BuildPrototype(v8::Isolate* isolate,
.SetMethod("focusOnWebView", &Window::FocusOnWebView)
.SetMethod("blurWebView", &Window::BlurWebView)
.SetMethod("isWebViewFocused", &Window::IsWebViewFocused)
.SetMethod("isDevToolsFocused", &Window::IsDevToolsFocused)
.SetMethod("capturePage", &Window::CapturePage)
.SetMethod("setProgressBar", &Window::SetProgressBar)
.SetMethod("setOverlayIcon", &Window::SetOverlayIcon)

View file

@ -78,8 +78,10 @@ class Window : public mate::TrackableObject<Window>,
bool IsDestroyed() const override;
private:
// mate::TrackableObject:
void Destroy() override;
// APIs for NativeWindow.
void Destroy();
void Close();
bool IsClosed();
void Focus();
@ -122,6 +124,7 @@ class Window : public mate::TrackableObject<Window>,
void FocusOnWebView();
void BlurWebView();
bool IsWebViewFocused();
bool IsDevToolsFocused();
void SetRepresentedFilename(const std::string& filename);
std::string GetRepresentedFilename();
void SetDocumentEdited(bool edited);

View file

@ -45,6 +45,7 @@ app.getHomeDir = -> @getPath 'home'
app.getDataPath = -> @getPath 'userData'
app.setDataPath = (path) -> @setPath 'userData', path
app.resolveProxy = -> @defaultSession.resolveProxy.apply @defaultSession, arguments
app.on 'activate', (event, hasVisibleWindows) -> @emit 'activate-with-no-open-windows' if not hasVisibleWindows
# Session wrapper.
sessionBindings._setWrapSession wrapSession

View file

@ -45,6 +45,9 @@ BrowserWindow::_init = ->
@on 'focus', (event) =>
app.emit 'browser-window-focus', event, this
# Notify the creation of the window.
app.emit 'browser-window-created', {}, this
BrowserWindow.getFocusedWindow = ->
windows = BrowserWindow.getAllWindows()
return window for window in windows when window.isFocused()

View file

@ -16,6 +16,11 @@ class NavigationController
constructor: (@webContents) ->
@clearHistory()
# webContents may have already navigated to a page.
if @webContents._getUrl()
@currentIndex++
@history.push @webContents._getUrl()
@webContents.on 'navigation-entry-commited', (event, url, inPage, replaceEntry) =>
if @inPageIndex > -1 and not inPage
# Navigated to a new page, clear in-page mark.

View file

@ -44,10 +44,8 @@ wrapWebContents = (webContents) ->
# Make sure webContents.executeJavaScript would run the code only when the
# web contents has been loaded.
webContents.loaded = false
webContents.once 'did-finish-load', -> @loaded = true
webContents.executeJavaScript = (code, hasUserGesture=false) ->
if @loaded
if @getUrl() and not @isLoading()
@_executeJavaScript code, hasUserGesture
else
webContents.once 'did-finish-load', @_executeJavaScript.bind(this, code, hasUserGesture)

View file

@ -29,7 +29,9 @@ class IDUserData : public base::SupportsUserData::Data {
} // namespace
TrackableObjectBase::TrackableObjectBase()
: weak_map_id_(0), wrapped_(nullptr) {
: weak_map_id_(0), wrapped_(nullptr), weak_factory_(this) {
RegisterDestructionCallback(
base::Bind(&TrackableObjectBase::Destroy, weak_factory_.GetWeakPtr()));
}
TrackableObjectBase::~TrackableObjectBase() {
@ -61,8 +63,9 @@ int32_t TrackableObjectBase::GetIDFromWrappedClass(base::SupportsUserData* w) {
}
// static
void TrackableObjectBase::RegisterDestructionCallback(void (*c)()) {
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(base::Bind(c));
void TrackableObjectBase::RegisterDestructionCallback(
const base::Closure& closure) {
atom::AtomBrowserMainParts::Get()->RegisterDestructionCallback(closure);
}
} // namespace mate

View file

@ -9,7 +9,9 @@
#include "atom/browser/api/event_emitter.h"
#include "atom/common/id_weak_map.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
namespace base {
class SupportsUserData;
@ -28,6 +30,9 @@ class TrackableObjectBase : public mate::EventEmitter {
// Wrap TrackableObject into a class that SupportsUserData.
void AttachAsUserData(base::SupportsUserData* wrapped);
// Subclasses should implement this to destroy their native types.
virtual void Destroy() = 0;
protected:
~TrackableObjectBase() override;
@ -39,12 +44,14 @@ class TrackableObjectBase : public mate::EventEmitter {
// Register a callback that should be destroyed before JavaScript environment
// gets destroyed.
static void RegisterDestructionCallback(void (*callback)());
static void RegisterDestructionCallback(const base::Closure& closure);
int32_t weak_map_id_;
base::SupportsUserData* wrapped_;
private:
base::WeakPtrFactory<TrackableObjectBase> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(TrackableObjectBase);
};
@ -85,7 +92,8 @@ class TrackableObject : public TrackableObjectBase {
}
TrackableObject() {
RegisterDestructionCallback(&TrackableObject<T>::ReleaseAllWeakReferences);
RegisterDestructionCallback(
base::Bind(&TrackableObject<T>::ReleaseAllWeakReferences));
}
// Removes this instance from the weak map.

View file

@ -15,8 +15,7 @@
#include "atom/browser/atom_speech_recognition_manager_delegate.h"
#include "atom/browser/browser.h"
#include "atom/browser/native_window.h"
#include "atom/browser/web_view_manager.h"
#include "atom/browser/web_view_constants.h"
#include "atom/browser/web_contents_preferences.h"
#include "atom/browser/window_list.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
@ -38,6 +37,7 @@
#include "net/ssl/ssl_cert_request_info.h"
#include "ppapi/host/ppapi_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "v8/include/v8.h"
namespace atom {
@ -54,37 +54,6 @@ bool g_suppress_renderer_process_restart = false;
// Custom schemes to be registered to standard.
std::string g_custom_schemes = "";
// Find out the owner of the child process according to |process_id|.
enum ProcessOwner {
OWNER_NATIVE_WINDOW,
OWNER_GUEST_WEB_CONTENTS,
OWNER_NONE, // it might be devtools though.
};
ProcessOwner GetProcessOwner(int process_id,
NativeWindow** window,
WebViewManager::WebViewInfo* info) {
content::WebContents* web_contents = content::WebContents::FromRenderViewHost(
content::RenderViewHost::FromID(process_id, kDefaultRoutingID));
if (!web_contents)
return OWNER_NONE;
// First search for NativeWindow.
*window = NativeWindow::FromWebContents(web_contents);
if (*window)
return OWNER_NATIVE_WINDOW;
// Then search for guest WebContents.
auto data = static_cast<WebViewManager::WebViewInfoUserData*>(
web_contents->GetUserData(web_view::kWebViewInfoKeyName));
if (data) {
*info = data->web_view_info();
return OWNER_GUEST_WEB_CONTENTS;
}
return OWNER_NONE;
}
scoped_refptr<net::X509Certificate> ImportCertFromFile(
const base::FilePath& path) {
if (path.empty())
@ -160,16 +129,7 @@ void AtomBrowserClient::OverrideWebkitPrefs(
// Custom preferences of guest page.
auto web_contents = content::WebContents::FromRenderViewHost(host);
auto info = static_cast<WebViewManager::WebViewInfoUserData*>(
web_contents->GetUserData(web_view::kWebViewInfoKeyName));
if (info) {
prefs->web_security_enabled = !info->web_view_info().disable_web_security;
return;
}
NativeWindow* window = NativeWindow::FromWebContents(web_contents);
if (window)
window->OverrideWebkitPrefs(prefs);
WebContentsPreferences::OverrideWebkitPrefs(web_contents, prefs);
}
std::string AtomBrowserClient::GetApplicationLocale() {
@ -225,23 +185,14 @@ void AtomBrowserClient::AppendExtraCommandLineSwitches(
if (ContainsKey(pending_processes_, process_id))
process_id = pending_processes_[process_id];
NativeWindow* window;
WebViewManager::WebViewInfo info;
ProcessOwner owner = GetProcessOwner(process_id, &window, &info);
// Get the WebContents of the render process.
content::WebContents* web_contents = content::WebContents::FromRenderViewHost(
content::RenderViewHost::FromID(process_id, kDefaultRoutingID));
if (!web_contents)
return;
if (owner == OWNER_NATIVE_WINDOW) {
window->AppendExtraCommandLineSwitches(command_line);
} else if (owner == OWNER_GUEST_WEB_CONTENTS) {
command_line->AppendSwitchASCII(
switches::kGuestInstanceID, base::IntToString(info.guest_instance_id));
command_line->AppendSwitchASCII(
switches::kNodeIntegration, info.node_integration ? "true" : "false");
if (info.plugins)
command_line->AppendSwitch(switches::kEnablePlugins);
if (!info.preload_script.empty())
command_line->AppendSwitchPath(
switches::kPreloadScript, info.preload_script);
}
WebContentsPreferences::AppendExtraCommandLineSwitches(
web_contents, command_line);
}
void AtomBrowserClient::DidCreatePpapiPlugin(

View file

@ -56,8 +56,10 @@ std::string RemoveWhitespace(const std::string& str) {
} // namespace
AtomBrowserContext::AtomBrowserContext()
: job_factory_(new AtomURLRequestJobFactory) {
AtomBrowserContext::AtomBrowserContext(const std::string& partition,
bool in_memory)
: brightray::BrowserContext(partition, in_memory),
job_factory_(new AtomURLRequestJobFactory) {
}
AtomBrowserContext::~AtomBrowserContext() {
@ -150,7 +152,7 @@ AtomBrowserContext::GetDownloadManagerDelegate() {
content::BrowserPluginGuestManager* AtomBrowserContext::GetGuestManager() {
if (!guest_manager_)
guest_manager_.reset(new WebViewManager(this));
guest_manager_.reset(new WebViewManager);
return guest_manager_.get();
}
@ -162,3 +164,13 @@ void AtomBrowserContext::RegisterPrefs(PrefRegistrySimple* pref_registry) {
}
} // namespace atom
namespace brightray {
// static
scoped_refptr<BrowserContext> BrowserContext::Create(
const std::string& partition, bool in_memory) {
return make_scoped_refptr(new atom::AtomBrowserContext(partition, in_memory));
}
} // namespace brightray

View file

@ -17,8 +17,8 @@ class WebViewManager;
class AtomBrowserContext : public brightray::BrowserContext {
public:
AtomBrowserContext();
virtual ~AtomBrowserContext();
AtomBrowserContext(const std::string& partition, bool in_memory);
~AtomBrowserContext() override;
// brightray::URLRequestContextGetter::Delegate:
std::string GetUserAgent() override;
@ -41,7 +41,8 @@ class AtomBrowserContext : public brightray::BrowserContext {
scoped_ptr<AtomDownloadManagerDelegate> download_manager_delegate_;
scoped_ptr<WebViewManager> guest_manager_;
AtomURLRequestJobFactory* job_factory_; // Weak reference.
// Managed by brightray::BrowserContext.
AtomURLRequestJobFactory* job_factory_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserContext);
};

View file

@ -13,6 +13,7 @@
#include "atom/browser/node_debugger.h"
#include "atom/common/api/atom_bindings.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/browser_process.h"
@ -22,27 +23,8 @@
#include "chrome/browser/ui/libgtk2ui/gtk2_util.h"
#endif
#include "atom/common/node_includes.h"
namespace atom {
namespace {
const base::FilePath::CharType kStoragePartitionDirname[] = "Partitions";
void GetStoragePartitionConfig(const GURL& partition,
base::FilePath* partition_path,
bool* in_memory,
std::string* id) {
*in_memory = (partition.path() != "/persist");
net::UnescapeRule::Type flags =
net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS;
*id = net::UnescapeURLComponent(partition.query(), flags);
*partition_path = base::FilePath(kStoragePartitionDirname).AppendASCII(*id);
}
} // namespace
// static
AtomBrowserMainParts* AtomBrowserMainParts::self_ = NULL;
@ -57,8 +39,6 @@ AtomBrowserMainParts::AtomBrowserMainParts()
}
AtomBrowserMainParts::~AtomBrowserMainParts() {
for (const auto& callback : destruction_callbacks_)
callback.Run();
}
// static
@ -67,30 +47,11 @@ AtomBrowserMainParts* AtomBrowserMainParts::Get() {
return self_;
}
content::BrowserContext* AtomBrowserMainParts::GetBrowserContextForPartition(
const GURL& partition) {
std::string id;
bool in_memory;
base::FilePath partition_path;
GetStoragePartitionConfig(partition, &partition_path, &in_memory, &id);
if (browser_context_map_.contains(id))
return browser_context_map_.get(id);
scoped_ptr<brightray::BrowserContext> browser_context(CreateBrowserContext());
browser_context->Initialize(partition_path.value(), in_memory);
browser_context_map_.set(id, browser_context.Pass());
return browser_context_map_.get(id);
}
void AtomBrowserMainParts::RegisterDestructionCallback(
const base::Closure& callback) {
destruction_callbacks_.push_back(callback);
}
brightray::BrowserContext* AtomBrowserMainParts::CreateBrowserContext() {
return new AtomBrowserContext();
}
void AtomBrowserMainParts::PostEarlyInitialization() {
brightray::BrowserMainParts::PostEarlyInitialization();
@ -155,4 +116,14 @@ void AtomBrowserMainParts::PreMainMessageLoopRun() {
#endif
}
void AtomBrowserMainParts::PostMainMessageLoopRun() {
brightray::BrowserMainParts::PostMainMessageLoopRun();
// Make sure destruction callbacks are called before message loop is
// destroyed, otherwise some objects that need to be deleted on IO thread
// won't be freed.
for (const auto& callback : destruction_callbacks_)
callback.Run();
}
} // namespace atom

View file

@ -6,11 +6,9 @@
#define ATOM_BROWSER_ATOM_BROWSER_MAIN_PARTS_H_
#include <list>
#include <map>
#include <string>
#include "base/callback.h"
#include "base/containers/scoped_ptr_hash_map.h"
#include "base/timer/timer.h"
#include "brightray/browser/browser_main_parts.h"
#include "content/public/browser/browser_context.h"
@ -33,10 +31,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
static AtomBrowserMainParts* Get();
// Returns the BrowserContext associated with the partition.
content::BrowserContext* GetBrowserContextForPartition(
const GURL& partition);
// Register a callback that should be destroyed before JavaScript environment
// gets destroyed.
void RegisterDestructionCallback(const base::Closure& callback);
@ -44,12 +38,10 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
Browser* browser() { return browser_.get(); }
protected:
// Implementations of brightray::BrowserMainParts.
brightray::BrowserContext* CreateBrowserContext() override;
// Implementations of content::BrowserMainParts.
// content::BrowserMainParts:
void PostEarlyInitialization() override;
void PreMainMessageLoopRun() override;
void PostMainMessageLoopRun() override;
#if defined(OS_MACOSX)
void PreMainMessageLoopStart() override;
void PostDestroyThreads() override;
@ -78,10 +70,6 @@ class AtomBrowserMainParts : public brightray::BrowserMainParts {
// List of callbacks should be executed before destroying JS env.
std::list<base::Closure> destruction_callbacks_;
// partition_id => browser_context
base::ScopedPtrHashMap<std::string, scoped_ptr<brightray::BrowserContext>>
browser_context_map_;
static AtomBrowserMainParts* self_;
DISALLOW_COPY_AND_ASSIGN(AtomBrowserMainParts);

View file

@ -94,8 +94,10 @@ void Browser::OpenURL(const std::string& url) {
FOR_EACH_OBSERVER(BrowserObserver, observers_, OnOpenURL(url));
}
void Browser::ActivateWithNoOpenWindows() {
FOR_EACH_OBSERVER(BrowserObserver, observers_, OnActivateWithNoOpenWindows());
void Browser::Activate(bool has_visible_windows) {
FOR_EACH_OBSERVER(BrowserObserver,
observers_,
OnActivate(has_visible_windows));
}
void Browser::WillFinishLaunching() {

View file

@ -108,8 +108,9 @@ class Browser : public WindowListObserver {
// Tell the application to open a url.
void OpenURL(const std::string& url);
// Tell the application that application is activated with no open windows.
void ActivateWithNoOpenWindows();
// Tell the application that application is activated with visible/invisible
// windows.
void Activate(bool has_visible_windows);
// Tell the application the loading has been done.
void WillFinishLaunching();

View file

@ -43,9 +43,9 @@ class BrowserObserver {
// Browser is used to open a url.
virtual void OnOpenURL(const std::string& url) {}
// The browser is activated with no open windows (usually by clicking on the
// dock icon).
virtual void OnActivateWithNoOpenWindows() {}
// The browser is activated with visible/invisible windows (usually by
// clicking on the dock icon).
virtual void OnActivate(bool has_visible_windows) {}
// The browser has finished loading.
virtual void OnWillFinishLaunching() {}

View file

@ -32,6 +32,7 @@ getExtensionInfoFromPath = (srcDirectory) ->
startPage: page
name: manifest.name
srcDirectory: srcDirectory
exposeExperimentalAPIs: true
extensionInfoMap[manifest.name]
# The loaded extensions cache and its persistent path.

View file

@ -38,29 +38,12 @@ moveLastToFirst = (list) ->
getNextInstanceId = (webContents) ->
++nextInstanceId
# Generate URL encoded partition id.
getPartitionId = (partition) ->
# Guest site url will be chrome-guest://fake-host/{persist}?{partitionId}
partitionId = "chrome-guest://fake-host/"
if partition
persist = partition.startsWith('persist:')
if persist
partition = partition.substring('persist:'.length)
partitionId += 'persist?'
else
# Just to differentiate from same persistant ID
partition += "_temp"
partitionId += '?'
partitionId += encodeURIComponent(partition)
return partitionId
# Create a new guest instance.
createGuest = (embedder, params) ->
webViewManager ?= process.atomBinding 'web_view_manager'
id = getNextInstanceId embedder
partitionId = getPartitionId params.partition
guest = webContents.create {isGuest: true, partition: partitionId, embedder}
guest = webContents.create {isGuest: true, partition: params.partition, embedder}
guestInstances[id] = {guest, embedder}
# Destroy guest when the embedder is gone or navigated.
@ -132,12 +115,13 @@ attachGuest = (embedder, elementInstanceId, guestInstanceId, params) ->
return unless guestInstances[oldGuestInstanceId]?
destroyGuest embedder, oldGuestInstanceId
webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest,
nodeIntegration: params.nodeintegration
plugins: params.plugins
disableWebSecurity: params.disablewebsecurity
preloadUrl: params.preload ? ''
partitionId: getPartitionId(params.partition)
webPreferences =
'guest-instance-id': guestInstanceId
'node-integration': params.nodeintegration ? false
'plugins': params.plugins
'web-security': !params.disablewebsecurity
webPreferences['preload-url'] = params.preload if params.preload
webViewManager.addGuest guestInstanceId, elementInstanceId, embedder, guest, webPreferences
guest.attachParams = params
embedderElementsMap[key] = guestInstanceId

View file

@ -52,12 +52,8 @@
- (BOOL)applicationShouldHandleReopen:(NSApplication*)theApplication
hasVisibleWindows:(BOOL)flag {
atom::Browser* browser = atom::Browser::Get();
if (flag) {
return YES;
} else {
browser->ActivateWithNoOpenWindows();
return NO;
}
browser->Activate(static_cast<bool>(flag));
return flag;
}
@end

View file

@ -15,12 +15,10 @@
#include "atom/common/native_mate_converters/image_converter.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/json/json_writer.h"
#include "base/prefs/pref_service.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/inspectable_web_contents.h"
#include "brightray/browser/inspectable_web_contents_view.h"
@ -31,8 +29,6 @@
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/renderer_preferences.h"
#include "content/public/common/web_preferences.h"
#include "ipc/ipc_message_macros.h"
#include "native_mate/dictionary.h"
#include "ui/gfx/codec/png_codec.h"
@ -43,10 +39,6 @@
#include "ui/gfx/screen.h"
#include "ui/gl/gpu_switching_manager.h"
#if defined(OS_WIN)
#include "ui/gfx/switches.h"
#endif
using content::NavigationEntry;
using content::RenderWidgetHostView;
using content::RenderWidgetHost;
@ -57,17 +49,6 @@ namespace atom {
namespace {
// Array of available web runtime features.
const char* kWebRuntimeFeatures[] = {
switches::kExperimentalFeatures,
switches::kExperimentalCanvasFeatures,
switches::kSubpixelFontScaling,
switches::kOverlayScrollbars,
switches::kOverlayFullscreenVideo,
switches::kSharedWorker,
switches::kPageVisibility,
};
// Convert draggable regions in raw format to SkRegion format. Caller is
// responsible for deleting the returned SkRegion instance.
scoped_ptr<SkRegion> DraggableRegionsToSkRegion(
@ -94,9 +75,7 @@ NativeWindow::NativeWindow(
transparent_(false),
enable_larger_than_screen_(false),
is_closed_(false),
node_integration_(true),
has_dialog_attached_(false),
zoom_factor_(1.0),
aspect_ratio_(0.0),
inspectable_web_contents_(inspectable_web_contents),
weak_factory_(this) {
@ -105,7 +84,6 @@ NativeWindow::NativeWindow(
options.Get(switches::kFrame, &has_frame_);
options.Get(switches::kTransparent, &transparent_);
options.Get(switches::kEnableLargerThanScreen, &enable_larger_than_screen_);
options.Get(switches::kNodeIntegration, &node_integration_);
// Tell the content module to initialize renderer widget with transparent
// mode.
@ -114,25 +92,6 @@ NativeWindow::NativeWindow(
// Read icon before window is created.
options.Get(switches::kIcon, &icon_);
// The "preload" option must be absolute path.
if (options.Get(switches::kPreloadScript, &preload_script_) &&
!preload_script_.IsAbsolute()) {
LOG(ERROR) << "Path of \"preload\" script must be absolute.";
preload_script_.clear();
}
// Be compatible with old API of "node-integration" option.
std::string old_string_token;
if (options.Get(switches::kNodeIntegration, &old_string_token) &&
old_string_token != "disable")
node_integration_ = true;
// Read the web preferences.
options.Get(switches::kWebPreferences, &web_preferences_);
// Read the zoom factor before any navigation.
options.Get(switches::kZoomFactor, &zoom_factor_);
WindowList::AddWindow(this);
}
@ -290,6 +249,10 @@ bool NativeWindow::IsWebViewFocused() {
return host_view && host_view->HasFocus();
}
bool NativeWindow::IsDevToolsFocused() {
return inspectable_web_contents_->GetView()->IsDevToolsViewFocused();
}
void NativeWindow::CapturePage(const gfx::Rect& rect,
const CapturePageCallback& callback) {
const auto view = web_contents()->GetRenderWidgetHostView();
@ -381,81 +344,6 @@ void NativeWindow::RendererResponsive(content::WebContents* source) {
FOR_EACH_OBSERVER(NativeWindowObserver, observers_, OnRendererResponsive());
}
void NativeWindow::AppendExtraCommandLineSwitches(
base::CommandLine* command_line) {
// Append --node-integration to renderer process.
command_line->AppendSwitchASCII(switches::kNodeIntegration,
node_integration_ ? "true" : "false");
// Append --preload.
if (!preload_script_.empty())
command_line->AppendSwitchPath(switches::kPreloadScript, preload_script_);
// Append --zoom-factor.
if (zoom_factor_ != 1.0)
command_line->AppendSwitchASCII(switches::kZoomFactor,
base::DoubleToString(zoom_factor_));
if (web_preferences_.IsEmpty())
return;
bool b;
#if defined(OS_WIN)
// Check if DirectWrite is disabled.
if (web_preferences_.Get(switches::kDirectWrite, &b) && !b)
command_line->AppendSwitch(::switches::kDisableDirectWrite);
#endif
// Check if plugins are enabled.
if (web_preferences_.Get("plugins", &b) && b)
command_line->AppendSwitch(switches::kEnablePlugins);
// This set of options are not availabe in WebPreferences, so we have to pass
// them via command line and enable them in renderer procss.
for (size_t i = 0; i < arraysize(kWebRuntimeFeatures); ++i) {
const char* feature = kWebRuntimeFeatures[i];
if (web_preferences_.Get(feature, &b))
command_line->AppendSwitchASCII(feature, b ? "true" : "false");
}
}
void NativeWindow::OverrideWebkitPrefs(content::WebPreferences* prefs) {
if (web_preferences_.IsEmpty())
return;
bool b;
std::vector<base::FilePath> list;
if (web_preferences_.Get("javascript", &b))
prefs->javascript_enabled = b;
if (web_preferences_.Get("images", &b))
prefs->images_enabled = b;
if (web_preferences_.Get("java", &b))
prefs->java_enabled = b;
if (web_preferences_.Get("text-areas-are-resizable", &b))
prefs->text_areas_are_resizable = b;
if (web_preferences_.Get("webgl", &b))
prefs->experimental_webgl_enabled = b;
if (web_preferences_.Get("webaudio", &b))
prefs->webaudio_enabled = b;
if (web_preferences_.Get("web-security", &b)) {
prefs->web_security_enabled = b;
prefs->allow_displaying_insecure_content = !b;
prefs->allow_running_insecure_content = !b;
}
if (web_preferences_.Get("allow-displaying-insecure-content", &b))
prefs->allow_displaying_insecure_content = b;
if (web_preferences_.Get("allow-running-insecure-content", &b))
prefs->allow_running_insecure_content = b;
if (web_preferences_.Get("extra-plugin-dirs", &list)) {
if (content::PluginService::GetInstance()->NPAPIPluginsSupported()) {
for (size_t i = 0; i < list.size(); ++i)
content::PluginService::GetInstance()->AddExtraPluginDir(list[i]);
} else {
LOG(WARNING) << "NPAPI plugins not supported on this platform";
}
}
}
void NativeWindow::NotifyWindowClosed() {
if (is_closed_)
return;

View file

@ -19,23 +19,17 @@
#include "content/public/browser/readback_types.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "native_mate/persistent_dictionary.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
class SkRegion;
namespace base {
class CommandLine;
}
namespace brightray {
class InspectableWebContents;
}
namespace content {
struct NativeWebKeyboardEvent;
struct WebPreferences;
}
namespace gfx {
@ -154,6 +148,7 @@ class NativeWindow : public content::WebContentsObserver,
virtual void FocusOnWebView();
virtual void BlurWebView();
virtual bool IsWebViewFocused();
virtual bool IsDevToolsFocused();
// Captures the page with |rect|, |callback| would be called when capturing is
// done.
@ -189,10 +184,6 @@ class NativeWindow : public content::WebContentsObserver,
content::WebContents*,
const content::NativeWebKeyboardEvent& event) {}
// Called when renderer process is going to be started.
void AppendExtraCommandLineSwitches(base::CommandLine* command_line);
void OverrideWebkitPrefs(content::WebPreferences* prefs);
// Public API used by platform-dependent delegates and observers to send UI
// related notifications.
void NotifyWindowClosed();
@ -282,9 +273,6 @@ class NativeWindow : public content::WebContentsObserver,
// The windows has been closed.
bool is_closed_;
// Whether node integration is enabled.
bool node_integration_;
// There is a dialog that has been attached to window.
bool has_dialog_attached_;
@ -292,15 +280,6 @@ class NativeWindow : public content::WebContentsObserver,
// it should be cancelled when we can prove that the window is responsive.
base::CancelableClosure window_unresposive_closure_;
// Web preferences.
mate::PersistentDictionary web_preferences_;
// The script to load before page's JavaScript starts to run.
base::FilePath preload_script_;
// Page's default zoom factor.
double zoom_factor_;
// Used to maintain the aspect ratio of a view which is inside of the
// content view.
double aspect_ratio_;

View file

@ -357,6 +357,17 @@ NativeWindowMac::NativeWindowMac(
styleMask |= NSTexturedBackgroundWindowMask;
}
std::string titleBarStyle = "default";
options.Get(switches::kTitleBarStyle, &titleBarStyle);
if (base::mac::IsOSYosemiteOrLater()) {
// New title bar styles are available in Yosemite or newer
if ((titleBarStyle == "hidden") || (titleBarStyle == "hidden-inset")) {
styleMask |= NSFullSizeContentViewWindowMask;
styleMask |= NSUnifiedTitleAndToolbarWindowMask;
}
}
window_.reset([[AtomNSWindow alloc]
initWithContentRect:cocoa_bounds
styleMask:styleMask
@ -382,6 +393,20 @@ NativeWindowMac::NativeWindowMac(
// We will manage window's lifetime ourselves.
[window_ setReleasedWhenClosed:NO];
// Configure title bar look on Yosemite or newer
if (base::mac::IsOSYosemiteOrLater()) {
if ((titleBarStyle == "hidden") || (titleBarStyle == "hidden-inset")) {
[window_ setTitlebarAppearsTransparent:YES];
[window_ setTitleVisibility:NSWindowTitleHidden];
if (titleBarStyle == "hidden-inset") {
NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"titlebarStylingToolbar"];
toolbar.showsBaselineSeparator = NO;
[window_ setToolbar:toolbar];
[toolbar release];
}
}
}
// On OS X the initial window size doesn't include window frame.
bool use_content_size = false;
options.Get(switches::kUseContentSize, &use_content_size);

View file

@ -46,7 +46,7 @@ class JsAsker : public RequestJob {
// Called by |CustomProtocolHandler| to store handler related information.
void SetHandlerInfo(
v8::Isolate* isolate,
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
net::URLRequestContextGetter* request_context_getter,
const JavaScriptHandler& handler) {
isolate_ = isolate;
request_context_getter_ = request_context_getter;
@ -57,7 +57,7 @@ class JsAsker : public RequestJob {
virtual void StartAsync(scoped_ptr<base::Value> options) = 0;
net::URLRequestContextGetter* request_context_getter() const {
return request_context_getter_.get();
return request_context_getter_;
}
private:
@ -89,7 +89,7 @@ class JsAsker : public RequestJob {
}
v8::Isolate* isolate_;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
net::URLRequestContextGetter* request_context_getter_;
JavaScriptHandler handler_;
base::WeakPtrFactory<JsAsker> weak_factory_;

View file

@ -6,13 +6,15 @@
#include <string>
#include "base/strings/string_number_conversions.h"
#include "net/base/net_errors.h"
namespace atom {
URLRequestBufferJob::URLRequestBufferJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate)
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate) {
: JsAsker<net::URLRequestSimpleJob>(request, network_delegate),
status_code_(net::HTTP_NOT_IMPLEMENTED) {
}
void URLRequestBufferJob::StartAsync(scoped_ptr<base::Value> options) {
@ -36,9 +38,28 @@ void URLRequestBufferJob::StartAsync(scoped_ptr<base::Value> options) {
data_ = new base::RefCountedBytes(
reinterpret_cast<const unsigned char*>(binary->GetBuffer()),
binary->GetSize());
status_code_ = net::HTTP_OK;
net::URLRequestSimpleJob::Start();
}
void URLRequestBufferJob::GetResponseInfo(net::HttpResponseInfo* info) {
std::string status("HTTP/1.1 ");
status.append(base::IntToString(status_code_));
status.append(" ");
status.append(net::GetHttpReasonPhrase(status_code_));
status.append("\0\0", 2);
net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status);
if (!mime_type_.empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(mime_type_);
headers->AddHeader(content_type_header);
}
info->headers = headers;
}
int URLRequestBufferJob::GetRefCountedData(
std::string* mime_type,
std::string* charset,

View file

@ -9,6 +9,7 @@
#include "atom/browser/net/js_asker.h"
#include "base/memory/ref_counted_memory.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_request_simple_job.h"
namespace atom {
@ -20,6 +21,9 @@ class URLRequestBufferJob : public JsAsker<net::URLRequestSimpleJob> {
// JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override;
// URLRequestJob:
void GetResponseInfo(net::HttpResponseInfo* info) override;
// URLRequestSimpleJob:
int GetRefCountedData(std::string* mime_type,
std::string* charset,
@ -30,6 +34,7 @@ class URLRequestBufferJob : public JsAsker<net::URLRequestSimpleJob> {
std::string mime_type_;
std::string charset_;
scoped_refptr<base::RefCountedBytes> data_;
net::HttpStatusCode status_code_;
DISALLOW_COPY_AND_ASSIGN(URLRequestBufferJob);
};

View file

@ -28,6 +28,20 @@ void URLRequestStringJob::StartAsync(scoped_ptr<base::Value> options) {
net::URLRequestSimpleJob::Start();
}
void URLRequestStringJob::GetResponseInfo(net::HttpResponseInfo* info) {
std::string status("HTTP/1.1 200 OK");
net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status);
if (!mime_type_.empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(mime_type_);
headers->AddHeader(content_type_header);
}
info->headers = headers;
}
int URLRequestStringJob::GetData(
std::string* mime_type,
std::string* charset,

View file

@ -19,6 +19,9 @@ class URLRequestStringJob : public JsAsker<net::URLRequestSimpleJob> {
// JsAsker:
void StartAsync(scoped_ptr<base::Value> options) override;
// URLRequestJob:
void GetResponseInfo(net::HttpResponseInfo* info) override;
// URLRequestSimpleJob:
int GetData(std::string* mime_type,
std::string* charset,

View file

@ -17,7 +17,7 @@
<key>CFBundleIconFile</key>
<string>atom.icns</string>
<key>CFBundleVersion</key>
<string>0.31.2</string>
<string>0.32.3</string>
<key>LSMinimumSystemVersion</key>
<string>10.8.0</string>
<key>NSMainNibFile</key>

View file

@ -56,8 +56,8 @@ END
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,31,2,0
PRODUCTVERSION 0,31,2,0
FILEVERSION 0,32,3,0
PRODUCTVERSION 0,32,3,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
@ -74,12 +74,12 @@ BEGIN
BEGIN
VALUE "CompanyName", "GitHub, Inc."
VALUE "FileDescription", "Electron"
VALUE "FileVersion", "0.31.2"
VALUE "FileVersion", "0.32.3"
VALUE "InternalName", "electron.exe"
VALUE "LegalCopyright", "Copyright (C) 2015 GitHub, Inc. All rights reserved."
VALUE "OriginalFilename", "electron.exe"
VALUE "ProductName", "Electron"
VALUE "ProductVersion", "0.31.2"
VALUE "ProductVersion", "0.32.3"
VALUE "SquirrelAwareVersion", "1"
END
END

View file

@ -0,0 +1,154 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_contents_preferences.h"
#include <string>
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_number_conversions.h"
#include "content/public/common/web_preferences.h"
#include "net/base/filename_util.h"
#if defined(OS_WIN)
#include "ui/gfx/switches.h"
#endif
DEFINE_WEB_CONTENTS_USER_DATA_KEY(atom::WebContentsPreferences);
namespace atom {
namespace {
// Array of available web runtime features.
const char* kWebRuntimeFeatures[] = {
switches::kExperimentalFeatures,
switches::kExperimentalCanvasFeatures,
switches::kSubpixelFontScaling,
switches::kOverlayScrollbars,
switches::kOverlayFullscreenVideo,
switches::kSharedWorker,
switches::kPageVisibility,
};
} // namespace
WebContentsPreferences::WebContentsPreferences(
content::WebContents* web_contents,
base::DictionaryValue* web_preferences) {
web_preferences_.Swap(web_preferences);
web_contents->SetUserData(UserDataKey(), this);
}
WebContentsPreferences::~WebContentsPreferences() {
}
void WebContentsPreferences::Merge(const base::DictionaryValue& extend) {
web_preferences_.MergeDictionary(&extend);
}
// static
void WebContentsPreferences::AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line) {
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return;
base::DictionaryValue& web_preferences = self->web_preferences_;
bool b;
#if defined(OS_WIN)
// Check if DirectWrite is disabled.
if (web_preferences.GetBoolean(switches::kDirectWrite, &b) && !b)
command_line->AppendSwitch(::switches::kDisableDirectWrite);
#endif
// Check if plugins are enabled.
if (web_preferences.GetBoolean("plugins", &b) && b)
command_line->AppendSwitch(switches::kEnablePlugins);
// This set of options are not availabe in WebPreferences, so we have to pass
// them via command line and enable them in renderer procss.
for (size_t i = 0; i < arraysize(kWebRuntimeFeatures); ++i) {
const char* feature = kWebRuntimeFeatures[i];
if (web_preferences.GetBoolean(feature, &b))
command_line->AppendSwitchASCII(feature, b ? "true" : "false");
}
// Check if we have node integration specified.
bool node_integration = true;
web_preferences.GetBoolean(switches::kNodeIntegration, &node_integration);
// Be compatible with old API of "node-integration" option.
std::string old_token;
if (web_preferences.GetString(switches::kNodeIntegration, &old_token) &&
old_token != "disable")
node_integration = true;
command_line->AppendSwitchASCII(switches::kNodeIntegration,
node_integration ? "true" : "false");
// The preload script.
base::FilePath::StringType preload;
if (web_preferences.GetString(switches::kPreloadScript, &preload)) {
if (base::FilePath(preload).IsAbsolute())
command_line->AppendSwitchNative(switches::kPreloadScript, preload);
else
LOG(ERROR) << "preload script must have abosulute path.";
} else if (web_preferences.GetString(switches::kPreloadUrl, &preload)) {
// Translate to file path if there is "preload-url" option.
base::FilePath preload_path;
if (net::FileURLToFilePath(GURL(preload), &preload_path))
command_line->AppendSwitchPath(switches::kPreloadScript, preload_path);
else
LOG(ERROR) << "preload url must be file:// protocol.";
}
// The zoom factor.
double zoom_factor = 1.0;
if (web_preferences.GetDouble(switches::kZoomFactor, &zoom_factor) &&
zoom_factor != 1.0)
command_line->AppendSwitchASCII(switches::kZoomFactor,
base::DoubleToString(zoom_factor));
// --guest-instance-id, which is used to identify guest WebContents.
int guest_instance_id;
if (web_preferences.GetInteger(switches::kGuestInstanceID,
&guest_instance_id))
command_line->AppendSwitchASCII(switches::kGuestInstanceID,
base::IntToString(guest_instance_id));
}
// static
void WebContentsPreferences::OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs) {
WebContentsPreferences* self = FromWebContents(web_contents);
if (!self)
return;
bool b;
if (self->web_preferences_.GetBoolean("javascript", &b))
prefs->javascript_enabled = b;
if (self->web_preferences_.GetBoolean("images", &b))
prefs->images_enabled = b;
if (self->web_preferences_.GetBoolean("java", &b))
prefs->java_enabled = b;
if (self->web_preferences_.GetBoolean("text-areas-are-resizable", &b))
prefs->text_areas_are_resizable = b;
if (self->web_preferences_.GetBoolean("webgl", &b))
prefs->experimental_webgl_enabled = b;
if (self->web_preferences_.GetBoolean("webaudio", &b))
prefs->webaudio_enabled = b;
if (self->web_preferences_.GetBoolean("web-security", &b)) {
prefs->web_security_enabled = b;
prefs->allow_displaying_insecure_content = !b;
prefs->allow_running_insecure_content = !b;
}
if (self->web_preferences_.GetBoolean("allow-displaying-insecure-content",
&b))
prefs->allow_displaying_insecure_content = b;
if (self->web_preferences_.GetBoolean("allow-running-insecure-content", &b))
prefs->allow_running_insecure_content = b;
}
} // namespace atom

View file

@ -0,0 +1,50 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_
#define ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_
#include "base/values.h"
#include "content/public/browser/web_contents_user_data.h"
namespace base {
class CommandLine;
}
namespace content {
struct WebPreferences;
}
namespace atom {
// Stores and applies the preferences of WebContents.
class WebContentsPreferences
: public content::WebContentsUserData<WebContentsPreferences> {
public:
// Append command paramters according to |web_contents|'s preferences.
static void AppendExtraCommandLineSwitches(
content::WebContents* web_contents, base::CommandLine* command_line);
// Modify the WebPreferences according to |web_contents|'s preferences.
static void OverrideWebkitPrefs(
content::WebContents* web_contents, content::WebPreferences* prefs);
WebContentsPreferences(content::WebContents* web_contents,
base::DictionaryValue* web_preferences);
~WebContentsPreferences() override;
// $.extend(|web_preferences_|, |new_web_preferences|).
void Merge(const base::DictionaryValue& new_web_preferences);
private:
friend class content::WebContentsUserData<WebContentsPreferences>;
base::DictionaryValue web_preferences_;
DISALLOW_COPY_AND_ASSIGN(WebContentsPreferences);
};
} // namespace atom
#endif // ATOM_BROWSER_WEB_CONTENTS_PREFERENCES_H_

View file

@ -1,24 +0,0 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/web_view_constants.h"
namespace atom {
namespace web_view {
const char kPreloadUrl[] = "preloadUrl";
const char kNodeIntegration[] = "nodeIntegration";
const char kPlugins[] = "plugins";
const char kDisableWebSecurity[] = "disableWebSecurity";
const char kPartitionId[] = "partitionId";
const int kDefaultWidth = 300;
const int kDefaultHeight = 300;
const char kWebViewInfoKeyName[] = "web_view_info";
} // namespace web_view
} // namespace atom

View file

@ -1,27 +0,0 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_
#define ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_
namespace atom {
namespace web_view {
extern const char kPreloadUrl[];
extern const char kNodeIntegration[];
extern const char kPlugins[];
extern const char kDisableWebSecurity[];
extern const char kPartitionId[];
extern const int kDefaultWidth;
extern const int kDefaultHeight;
extern const char kWebViewInfoKeyName[];
} // namespace web_view
} // namespace atom
#endif // ATOM_BROWSER_WEB_VIEW_CONSTANTS_H_

View file

@ -5,7 +5,6 @@
#include "atom/browser/web_view_guest_delegate.h"
#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_view_constants.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "content/public/browser/guest_host.h"
#include "content/public/browser/render_frame_host.h"
@ -14,6 +13,13 @@
namespace atom {
namespace {
const int kDefaultWidth = 300;
const int kDefaultHeight = 300;
} // namespace
WebViewGuestDelegate::WebViewGuestDelegate()
: guest_opaque_(true),
guest_host_(nullptr),
@ -172,7 +178,7 @@ gfx::Size WebViewGuestDelegate::GetDefaultSize() const {
return embedder_web_contents_->GetRenderWidgetHostView()
->GetVisibleViewportSize();
} else {
return gfx::Size(web_view::kDefaultWidth, web_view::kDefaultHeight);
return gfx::Size(kDefaultWidth, kDefaultHeight);
}
}

View file

@ -5,13 +5,12 @@
#include "atom/browser/web_view_manager.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents.h"
namespace atom {
WebViewManager::WebViewManager(content::BrowserContext* context) {
WebViewManager::WebViewManager() {
}
WebViewManager::~WebViewManager() {
@ -21,7 +20,6 @@ void WebViewManager::AddGuest(int guest_instance_id,
int element_instance_id,
content::WebContents* embedder,
content::WebContents* web_contents) {
base::AutoLock auto_lock(lock_);
web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder };
// Map the element in embedder to guest.
@ -31,7 +29,6 @@ void WebViewManager::AddGuest(int guest_instance_id,
}
void WebViewManager::RemoveGuest(int guest_instance_id) {
base::AutoLock auto_lock(lock_);
if (!ContainsKey(web_contents_embedder_map_, guest_instance_id))
return;

View file

@ -7,45 +7,14 @@
#include <map>
#include "base/files/file_path.h"
#include "base/supports_user_data.h"
#include "base/synchronization/lock.h"
#include "content/public/browser/browser_plugin_guest_manager.h"
#include "content/public/browser/site_instance.h"
namespace content {
class BrowserContext;
class RenderProcessHost;
}
namespace atom {
class WebViewManager : public content::BrowserPluginGuestManager {
public:
struct WebViewInfo {
int guest_instance_id;
content::WebContents* embedder;
bool node_integration;
bool plugins;
bool disable_web_security;
base::FilePath preload_script;
GURL partition_id;
};
class WebViewInfoUserData : public base::SupportsUserData::Data {
public:
explicit WebViewInfoUserData(WebViewInfo info)
: web_view_info_(info) {}
~WebViewInfoUserData() override {}
WebViewInfo& web_view_info() { return web_view_info_; }
private:
WebViewInfo web_view_info_;
};
explicit WebViewManager(content::BrowserContext* context);
virtual ~WebViewManager();
WebViewManager();
~WebViewManager() override;
void AddGuest(int guest_instance_id,
int element_instance_id,
@ -90,8 +59,6 @@ class WebViewManager : public content::BrowserPluginGuestManager {
// (embedder_process_id, element_instance_id) => guest_instance_id
std::map<ElementInstanceKey, int> element_instance_id_to_guest_map_;
base::Lock lock_;
DISALLOW_COPY_AND_ASSIGN(WebViewManager);
};

View file

@ -10,13 +10,12 @@
#include "atom/common/asar/archive.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "native_mate/arguments.h"
#include "native_mate/dictionary.h"
#include "native_mate/object_template_builder.h"
#include "native_mate/wrappable.h"
#include "atom/common/node_includes.h"
namespace {
class Archive : public mate::Wrappable {

View file

@ -7,9 +7,8 @@
#include "atom/common/platform_util.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "native_mate/dictionary.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
namespace {

View file

@ -3,11 +3,10 @@
// found in the LICENSE file.
#include "atom/common/api/object_life_monitor.h"
#include "atom/common/node_includes.h"
#include "native_mate/dictionary.h"
#include "v8/include/v8-profiler.h"
#include "atom/common/node_includes.h"
namespace {
v8::Local<v8::Object> CreateObjectWithName(v8::Isolate* isolate,

View file

@ -5,11 +5,10 @@
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/api/locker.h"
#include "atom/common/node_includes.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
#include "atom/common/node_includes.h"
namespace mate {
namespace internal {

View file

@ -6,8 +6,8 @@
#define ATOM_VERSION_H
#define ATOM_MAJOR_VERSION 0
#define ATOM_MINOR_VERSION 31
#define ATOM_PATCH_VERSION 2
#define ATOM_MINOR_VERSION 32
#define ATOM_PATCH_VERSION 3
#define ATOM_VERSION_IS_RELEASE 1

View file

@ -37,13 +37,18 @@ wrapWithActivateUvLoop = (func) ->
process.activateUvLoop()
func.apply this, arguments
process.nextTick = wrapWithActivateUvLoop process.nextTick
global.setImmediate = wrapWithActivateUvLoop timers.setImmediate
global.clearImmediate = timers.clearImmediate
# setTimeout needs to update the polling timeout of the event loop, when called
# under Chromium's event loop the node's event loop won't get a chance to update
# the timeout, so we have to force the node's event loop to recalculate the
# timeout in browser process.
if process.type is 'browser'
# setTimeout needs to update the polling timeout of the event loop, when
# called under Chromium's event loop the node's event loop won't get a chance
# to update the timeout, so we have to force the node's event loop to
# recalculate the timeout in browser process.
global.setTimeout = wrapWithActivateUvLoop timers.setTimeout
global.setInterval = wrapWithActivateUvLoop timers.setInterval
global.setImmediate = wrapWithActivateUvLoop timers.setImmediate
global.clearImmediate = wrapWithActivateUvLoop timers.clearImmediate
else
# There are no setImmediate under renderer process by default, so we need to
# manually setup them here.
global.setImmediate = setImmediate
global.clearImmediate = clearImmediate

View file

@ -11,6 +11,7 @@
#include "atom/common/api/locker.h"
#include "atom/common/atom_command_line.h"
#include "atom/common/native_mate_converters/file_path_converter.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/base_paths.h"
#include "base/files/file_path.h"
@ -21,8 +22,6 @@
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
#include "atom/common/node_includes.h"
using content::BrowserThread;
// Force all builtin modules to be referenced so they can actually run their

View file

@ -5,6 +5,8 @@
#ifndef ATOM_COMMON_NODE_INCLUDES_H_
#define ATOM_COMMON_NODE_INCLUDES_H_
#include "base/logging.h"
// Include common headers for using node APIs.
#define BUILDING_NODE_EXTENSION

View file

@ -42,6 +42,9 @@ const char kAcceptFirstMouse[] = "accept-first-mouse";
// Whether window size should include window frame.
const char kUseContentSize[] = "use-content-size";
// The requested title bar style for the window
const char kTitleBarStyle[] = "title-bar-style";
// The WebPreferences.
const char kWebPreferences[] = "web-preferences";
@ -75,6 +78,9 @@ const char kGuestInstanceID[] = "guest-instance-id";
// Script that will be loaded by guest WebContents before other scripts.
const char kPreloadScript[] = "preload";
// Like --preload, but the passed argument is an URL.
const char kPreloadUrl[] = "preload-url";
// Whether the window should be transparent.
const char kTransparent[] = "transparent";

View file

@ -30,6 +30,7 @@ extern const char kAlwaysOnTop[];
extern const char kNodeIntegration[];
extern const char kAcceptFirstMouse[];
extern const char kUseContentSize[];
extern const char kTitleBarStyle[];
extern const char kWebPreferences[];
extern const char kZoomFactor[];
extern const char kAutoHideMenuBar[];
@ -41,6 +42,7 @@ extern const char kPpapiFlashPath[];
extern const char kPpapiFlashVersion[];
extern const char kGuestInstanceID[];
extern const char kPreloadScript[];
extern const char kPreloadUrl[];
extern const char kTransparent[];
extern const char kType[];
extern const char kDisableAutoHideCursor[];

View file

@ -5,13 +5,12 @@
#include "atom/common/api/api_messages.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "content/public/renderer/render_view.h"
#include "native_mate/dictionary.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "atom/common/node_includes.h"
using content::RenderView;
using blink::WebLocalFrame;
using blink::WebView;
@ -30,7 +29,7 @@ RenderView* GetCurrentRenderView() {
return RenderView::FromWebView(view);
}
void Send(v8::Isolate* isolate,
void Send(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
RenderView* render_view = GetCurrentRenderView();
@ -41,10 +40,10 @@ void Send(v8::Isolate* isolate,
render_view->GetRoutingID(), channel, arguments));
if (!success)
node::ThrowError(isolate, "Unable to send AtomViewHostMsg_Message");
args->ThrowError("Unable to send AtomViewHostMsg_Message");
}
base::string16 SendSync(v8::Isolate* isolate,
base::string16 SendSync(mate::Arguments* args,
const base::string16& channel,
const base::ListValue& arguments) {
base::string16 json;
@ -60,7 +59,7 @@ base::string16 SendSync(v8::Isolate* isolate,
bool success = render_view->Send(message);
if (!success)
node::ThrowError(isolate, "Unable to send AtomViewHostMsg_Message_Sync");
args->ThrowError("Unable to send AtomViewHostMsg_Message_Sync");
return json;
}

View file

@ -13,6 +13,7 @@
#include "atom/common/api/api_messages.h"
#include "atom/common/api/event_emitter_caller.h"
#include "atom/common/native_mate_converters/value_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_renderer_client.h"
#include "base/command_line.h"
@ -31,8 +32,6 @@
#include "third_party/WebKit/public/web/WebView.h"
#include "ui/base/resource/resource_bundle.h"
#include "atom/common/node_includes.h"
namespace atom {
namespace {

View file

@ -7,11 +7,12 @@
#include <string>
#include "atom/common/api/atom_bindings.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/node_bindings.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "atom/renderer/atom_render_view_observer.h"
#include "atom/renderer/guest_view_container.h"
#include "atom/renderer/node_array_buffer_bridge.h"
#include "base/command_line.h"
#include "chrome/renderer/pepper/pepper_helper.h"
#include "chrome/renderer/printing/print_web_view_helper.h"
@ -20,16 +21,12 @@
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
#include "content/public/renderer/render_thread.h"
#include "third_party/WebKit/public/web/WebArrayBuffer.h"
#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
#include "third_party/WebKit/public/web/WebCustomElement.h"
#include "third_party/WebKit/public/web/WebLocalFrame.h"
#include "third_party/WebKit/public/web/WebPluginParams.h"
#include "third_party/WebKit/public/web/WebKit.h"
#include "third_party/WebKit/public/web/WebRuntimeFeatures.h"
#include "atom/common/node_includes.h"
#if defined(OS_WIN)
#include <shlobj.h>
#endif
@ -51,37 +48,6 @@ bool IsSwitchEnabled(base::CommandLine* command_line,
return true;
}
// global.Uint8Array;
v8::Local<v8::Function> GetUint8ArrayConstructor(
v8::Isolate* isolate, v8::Local<v8::Context> context) {
v8::Local<v8::Value> constructor = context->Global()->Get(
mate::StringToV8(isolate, "Uint8Array"));
return v8::Local<v8::Function>::Cast(constructor);
}
// new ArrayBuffer(size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferCreate(
v8::Isolate* isolate, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::create(size, 1);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new Uint8Array(array_buffer, offset, size);
v8::Local<v8::Uint8Array> BlinkUint8ArrayCreate(
v8::Local<v8::ArrayBuffer> ab, size_t offset, size_t size) {
v8::Local<v8::Context> context = ab->CreationContext();
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Function> constructor =
GetUint8ArrayConstructor(isolate, context);
v8::Local<v8::Value> args[] = {
ab, mate::ConvertToV8(isolate, offset), mate::ConvertToV8(isolate, size)
};
return v8::Local<v8::Uint8Array>::Cast(constructor->NewInstance(
context, arraysize(args), args).ToLocalChecked());
}
// Helper class to forward the messages to the client.
class AtomRenderFrameObserver : public content::RenderFrameObserver {
public:
@ -120,9 +86,7 @@ void AtomRendererClient::WebKitInitialized() {
blink::WebCustomElement::addEmbedderCustomElementName("webview");
blink::WebCustomElement::addEmbedderCustomElementName("browserplugin");
// Override Node's ArrayBuffer with DOM's ArrayBuffer.
node::Buffer::SetArrayBufferCreator(&BlinkArrayBufferCreate,
&BlinkUint8ArrayCreate);
OverrideNodeArrayBuffer();
node_bindings_->Initialize();
node_bindings_->PrepareMessageLoop();

View file

@ -6,7 +6,7 @@ requestId = 0
WEB_VIEW_EVENTS =
'load-commit': ['url', 'isMainFrame']
'did-finish-load': []
'did-fail-load': ['errorCode', 'errorDescription']
'did-fail-load': ['errorCode', 'errorDescription', 'validatedUrl']
'did-frame-finish-load': ['isMainFrame']
'did-start-loading': []
'did-stop-loading': []

View file

@ -0,0 +1,66 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/renderer/node_array_buffer_bridge.h"
#include "base/basictypes.h"
#include "atom/common/node_includes.h"
#include "native_mate/converter.h"
#include "third_party/WebKit/public/web/WebArrayBuffer.h"
#include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
namespace atom {
namespace {
// global.Uint8Array;
v8::Local<v8::Function> GetUint8ArrayConstructor(
v8::Isolate* isolate, v8::Local<v8::Context> context) {
v8::Local<v8::Value> constructor = context->Global()->Get(
mate::StringToV8(isolate, "Uint8Array"));
return v8::Local<v8::Function>::Cast(constructor);
}
// new ArrayBuffer(size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferNew(
v8::Isolate* isolate, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::create(size, 1);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new ArrayBuffer(data, size);
v8::Local<v8::ArrayBuffer> BlinkArrayBufferNewWith(
v8::Isolate* isolate, void* data, size_t size) {
blink::WebArrayBuffer buffer = blink::WebArrayBuffer::createExternal(
data, size);
return v8::Local<v8::ArrayBuffer>::Cast(
blink::WebArrayBufferConverter::toV8Value(
&buffer, isolate->GetCurrentContext()->Global(), isolate));
}
// new Uint8Array(array_buffer, offset, size);
v8::Local<v8::Uint8Array> BlinkUint8ArrayNew(
v8::Local<v8::ArrayBuffer> ab, size_t offset, size_t size) {
// Use the DOM's Uint8Array constructor to create Uint8Array.
v8::Local<v8::Context> context = ab->CreationContext();
v8::Isolate* isolate = context->GetIsolate();
v8::Local<v8::Function> constructor =
GetUint8ArrayConstructor(isolate, context);
v8::Local<v8::Value> args[] = {
ab, mate::ConvertToV8(isolate, offset), mate::ConvertToV8(isolate, size)
};
return v8::Local<v8::Uint8Array>::Cast(constructor->NewInstance(
context, arraysize(args), args).ToLocalChecked());
}
} // namespace
void OverrideNodeArrayBuffer() {
node::Buffer::SetArrayBufferCreator(
BlinkArrayBufferNew, BlinkArrayBufferNewWith, BlinkUint8ArrayNew);
}
} // namespace atom

View file

@ -0,0 +1,15 @@
// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_
#define ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_
namespace atom {
// Override Node's ArrayBuffer with DOM's ArrayBuffer.
void OverrideNodeArrayBuffer();
} // namespace atom
#endif // ATOM_RENDERER_NODE_ARRAY_BUFFER_BRIDGE_H_

View file

@ -75,6 +75,7 @@
'xcode_settings': {
'GCC_TREAT_WARNINGS_AS_ERRORS': 'NO',
'WARNING_CFLAGS': [
'-Wno-unknown-warning-option',
'-Wno-parentheses-equality',
'-Wno-unused-function',
'-Wno-sometimes-uninitialized',

View file

@ -1,68 +0,0 @@
## Guías
* [Distribución de aplicaciones](tutorial/application-distribution-es.md)
* [Empaquetamiento de aplicaciones](tutorial/application-packaging-es.md)
* [Utilizando módulos nativos](tutorial/using-native-node-modules-es.md)
* [Depurando el proceso principal](tutorial/debugging-main-process-es.md)
* [Utilizando Selenium y WebDriver](tutorial/using-selenium-and-webdriver-es.md)
* [Extensión DevTools](tutorial/devtools-extension-es.md)
* [Utilizando el plugin pepper flash](tutorial/using-pepper-flash-plugin-es.md)
## Tutoriales
* [Introducción](tutorial/quick-start.md)
* [Integración con el entorno de escritorio](tutorial/desktop-environment-integration.md)
* [Detección del evento en línea/fuera de línea](tutorial/online-offline-events.md)
## API
* [Sinopsis](api/synopsis.md)
* [Proceso](api/process.md)
* [Parámetros CLI soportados (Chrome)](api/chrome-command-line-switches.md)
Elementos DOM customizados:
* [Objeto `File`](api/file-object.md)
* [Etiqueta `<webview>`](api/web-view-tag.md)
* [Función `window.open`](api/window-open.md)
Módulos del proceso principal:
* [app](api/app.md)
* [auto-updater](api/auto-updater.md)
* [browser-window](api/browser-window.md)
* [content-tracing](api/content-tracing.md)
* [dialog](api/dialog.md)
* [global-shortcut](api/global-shortcut.md)
* [ipc (main process)](api/ipc-main-process.md)
* [menu](api/menu.md)
* [menu-item](api/menu-item.md)
* [power-monitor](api/power-monitor.md)
* [power-save-blocker](api/power-save-blocker.md)
* [protocol](api/protocol.md)
* [tray](api/tray.md)
Módulos del renderer (página web):
* [ipc (renderer)](api/ipc-renderer.md)
* [remote](api/remote.md)
* [web-frame](api/web-frame.md)
Módulos de ambos procesos:
* [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md)
* [native-image](api/native-image.md)
* [screen](api/screen.md)
* [shell](api/shell.md)
## Desarrollo
* [Guía de estilo](development/coding-style.md)
* [Estructura de directorio](development/source-code-directory-structure.md)
* [Diferencias técnicas con NW.js (anteriormente conocido como node-webkit)](development/atom-shell-vs-node-webkit.md)
* [Sistema de compilación](development/build-system-overview.md)
* [Instrucciones de compilación (Mac)](development/build-instructions-osx.md)
* [Instrucciones de compilación (Windows)](development/build-instructions-windows.md)
* [Instrucciones de compilación (Linux)](development/build-instructions-linux.md)
* [Configurando un servidor de símbolos en el depurador](development/setting-up-symbol-server.md)

View file

@ -0,0 +1,68 @@
## Guías
* [Distribución de aplicaciones](tutorial/application-distribution.md)
* [Empaquetamiento de aplicaciones](tutorial/application-packaging.md)
* [Utilizando módulos nativos](tutorial/using-native-node-modules.md)
* [Depurando el proceso principal](tutorial/debugging-main-process.md)
* [Utilizando Selenium y WebDriver](tutorial/using-selenium-and-webdriver.md)
* [Extensión DevTools](tutorial/devtools-extension.md)
* [Utilizando el plugin pepper flash](tutorial/using-pepper-flash-plugin.md)
## Tutoriales
* [Introducción](../../docs/tutorial/quick-start.md)
* [Integración con el entorno de escritorio](../../docs/tutorial/desktop-environment-integration.md)
* [Detección del evento en línea/fuera de línea](../../docs/tutorial/online-offline-events.md)
## API
* [Sinopsis](../../docs/api/synopsis.md)
* [Proceso](../../docs/api/process.md)
* [Parámetros CLI soportados (Chrome)](../../docs/api/chrome-command-line-switches.md)
Elementos DOM customizados:
* [Objeto `File`](../../docs/api/file-object.md)
* [Etiqueta `<webview>`](../../docs/api/web-view-tag.md)
* [Función `window.open`](../../docs/api/window-open.md)
Módulos del proceso principal:
* [app](../../docs/api/app.md)
* [auto-updater](../../docs/api/auto-updater.md)
* [browser-window](../../docs/api/browser-window.md)
* [content-tracing](../../docs/api/content-tracing.md)
* [dialog](../../docs/api/dialog.md)
* [global-shortcut](../../docs/api/global-shortcut.md)
* [ipc (main process)](../../docs/api/ipc-main-process.md)
* [menu](../../docs/api/menu.md)
* [menu-item](../../docs/api/menu-item.md)
* [power-monitor](../../docs/api/power-monitor.md)
* [power-save-blocker](../../docs/api/power-save-blocker.md)
* [protocol](../../docs/api/protocol.md)
* [tray](../../docs/api/tray.md)
Módulos del renderer (página web):
* [ipc (renderer)](../../docs/api/ipc-renderer.md)
* [remote](../../docs/api/remote.md)
* [web-frame](../../docs/api/web-frame.md)
Módulos de ambos procesos:
* [clipboard](../../docs/api/clipboard.md)
* [crash-reporter](../../docs/api/crash-reporter.md)
* [native-image](../../docs/api/native-image.md)
* [screen](../../docs/api/screen.md)
* [shell](../../docs/api/shell.md)
## Desarrollo
* [Guía de estilo](../../docs/development/coding-style.md)
* [Estructura de directorio](../../docs/development/source-code-directory-structure.md)
* [Diferencias técnicas con NW.js (anteriormente conocido como node-webkit)](../../docs/development/atom-shell-vs-node-webkit.md)
* [Sistema de compilación](../../docs/development/build-system-overview.md)
* [Instrucciones de compilación (Mac)](../../docs/development/build-instructions-osx.md)
* [Instrucciones de compilación (Windows)](../../docs/development/build-instructions-windows.md)
* [Instrucciones de compilación (Linux)](../../docs/development/build-instructions-linux.md)
* [Configurando un servidor de símbolos en el depurador](../../docs/development/setting-up-symbol-server.md)

View file

@ -2,7 +2,7 @@
* [어플리케이션 배포](tutorial/application-distribution.md)
* [어플리케이션 패키징](tutorial/application-packaging.md)
* [네이티브 node 모듈 사용하기](tutorial/using-native-node-modules.md)
* [네이티브 Node 모듈 사용하기](tutorial/using-native-node-modules.md)
* [메인 프로세스 디버깅하기](tutorial/debugging-main-process.md)
* [Selenium 과 WebDriver 사용하기](tutorial/using-selenium-and-webdriver.md)
* [개발자 콘솔 확장기능](tutorial/devtools-extension.md)
@ -12,25 +12,25 @@
* [시작하기](tutorial/quick-start.md)
* [데스크톱 환경 통합](tutorial/desktop-environment-integration.md)
* [온라인/오프라인 이벤트](tutorial/online-offline-events.md)
* [온라인/오프라인 이벤트 감지](tutorial/online-offline-events.md)
## API 레퍼런스
* [개요](api/synopsis.md)
* [process](api/process.md)
* [크롬 Command-Line 스위치 지원](api/chrome-command-line-switches.md)
* [Process 객체](api/process.md)
* [크롬 Command Line 스위치 지원](api/chrome-command-line-switches.md)
커스텀 DOM elements:
### 커스텀 DOM elements:
* [`File` 객체](api/file-object.md)
* [`<webview>` 태그](api/web-view-tag.md)
* [`window.open` 메서드](api/window-open.md)
* [`window.open` 함수](api/window-open.md)
메인 프로세스를 위한 모듈들:
### 메인 프로세스를 위한 모듈들:
* [app](api/app.md)
* [app (0% 번역됨)](api/app.md)
* [auto-updater](api/auto-updater.md)
* [browser-window](api/browser-window.md)
* [browser-window (0% 번역됨)](api/browser-window.md)
* [content-tracing](api/content-tracing.md)
* [dialog](api/dialog.md)
* [global-shortcut](api/global-shortcut.md)
@ -41,16 +41,16 @@
* [power-save-blocker](api/power-save-blocker.md)
* [protocol](api/protocol.md)
* [session](api/session.md)
* [webContents](api/web-contents.md)
* [web-contents (0% 번역됨)](api/web-contents.md)
* [tray](api/tray.md)
랜더러 프로세스를 위한 모듈들 (웹 페이지):
### 랜더러 프로세스를 위한 모듈들 (웹 페이지):
* [ipc (renderer)](api/ipc-renderer.md)
* [remote](api/remote.md)
* [web-frame](api/web-frame.md)
두 프로세스에서 모두 사용 가능한 모듈들:
### 두 프로세스에서 모두 사용 가능한 모듈들:
* [clipboard](api/clipboard.md)
* [crash-reporter](api/crash-reporter.md)

View file

@ -38,7 +38,7 @@ Squirrel은 응답을 분석해야 할 책임이 있기 때문에 `Accept: appli
버전 식별자와 다른 기준을 특정하는 업데이트 요청 폼을 서버로 전달하기 위한 공통적인 방법으로 쿼리 인자를 사용하는 방법이 있습니다:
```javascript
// On the main process
// In the main process
var app = require('app');
var autoUpdater = require('auto-updater');
autoUpdater.setFeedUrl('http://mycompany.com/myapp/latest?version=' + app.getVersion());

View file

@ -15,7 +15,7 @@ contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() {
});
}, 5000);
});
``
```
## Methods
@ -29,10 +29,11 @@ contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, function() {
모든 child 프로세스가 `getCategories` 요청을 승인하면 `callback`이 한 번 호출되며 인자에 카테고리 그룹의 배열이 전달됩니다.
### `contentTracing.startRecording(categoryFilter, traceOptions, callback)`
### `contentTracing.startRecording(options, callback)`
* `categoryFilter` String
* `traceOptions` String
* `options` Object
* `categoryFilter` String
* `traceOptions` String
* `callback` Function
모든 프로세스에서 레코딩을 시작합니다.
@ -85,10 +86,11 @@ Child 프로세스는 일반적으로 추적 데이터와 희귀한 플러시
추적 데이터는 `resultFilePath` 해당 경로가 비어있는 경우에 한 해 해당 경로에 작성되거나 임시 파일에 작성됩니다.
실제 파일 경로는 null이 아닌 이상 `callback`을 통해 전달됩니다.
### `contentTracing.startMonitoring(categoryFilter, traceOptions, callback)`
### `contentTracing.startMonitoring(options, callback)`
* `categoryFilter` String
* `traceOptions` String
* `options` Object
* `categoryFilter` String
* `traceOptions` String
* `callback` Function
모든 프로세스에서 모니터링을 시작합니다.

View file

@ -13,6 +13,16 @@ var BrowserWindow = require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600, frame: false });
```
### 최신 Mac에서 사용할 수 있는 대안
OS X 10.10 Yosemite 이후의 최신 버전부터는 테두리가 없는 창을 만들 때 새로운 방법을 사용할 수 있습니다.
`frame` 옵션을 `false`로 지정하여 제목과 창 구성 요소를 모두 비활성화하는 대신 새로운 `title-bar-style`
옵션을 통해 제목만 숨기고 창 구성 요소("흔히 신호등으로 알고 있는")의 기능과 창 크기를 그대로 유지할 수 있습니다:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600, 'title-bar-style': 'hidden' });
## 투명한 창 만들기
Frameless Window의 창의 배경을 투명하게 만들고 싶다면 `transparent` 옵션을 `true`로 바꿔주기만 하면됩니다:

View file

@ -6,7 +6,7 @@
## 메시지 전송
물론 메인 프로세스에서 랜더러 프로세스로 메시지를 보내는 것도 가능합니다.
자세한 내용은 [WebContents.send](browser-window.md#webcontentssendchannel-args)를 참고하세요.
자세한 내용은 [WebContents.send](web-contents.md#webcontentssendchannel-args)를 참고하세요.
- 메시지를 전송할 때 이벤트 이름은 `channel`이 됩니다.
- 메시지에 동기로 응답할 땐 반드시 `event.returnValue`를 설정해야 합니다.

View file

@ -164,11 +164,11 @@ if (process.platform == 'darwin') {
{
label: 'Hide Others',
accelerator: 'Command+Shift+H',
role: 'hideothers:'
role: 'hideothers'
},
{
label: 'Show All',
role: 'unhide:'
role: 'unhide'
},
{
type: 'separator'
@ -295,7 +295,7 @@ OS X에선 지정한 어플리케이션 메뉴에 상관없이 메뉴의 첫번
만약 참조된 아이템의 분리자 그룹이 존재하지 않을 경우 지정된 id로 새로운 분리자 그룹을 만든 후 해당 그룹의 뒤에 삽입됩니다.
위치를 지정한 아이템의 뒤에 위치가 지정되지 않은 아이템이 있을 경우 각 아이템의 위치가 지정되기 전까지 모든 아이템이 위치가 지정된 아이템의 뒤에 삽입됩니다.
이에 따라 위치를 이동하고 싶은 특정 그룹의 아이템들이 있을 경우 해당 그룹의 맨 첫번째 메뉴 아이템의 위치만을 지정하면 됩니다.
따라 위치를 이동하고 싶은 특정 그룹의 아이템들이 있을 경우 해당 그룹의 맨 첫번째 메뉴 아이템의 위치만을 지정하면 됩니다.
### 예제

View file

@ -17,7 +17,7 @@ var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl('https://github.com');
```
**참고:** 반대로 메인 프로세스에서 랜더러 프로세스에 접근 하려면 [webContents.executeJavascript](browser-window.md#webcontents-executejavascript-code) 메서드를 사용하면 됩니다.
**참고:** 반대로 메인 프로세스에서 랜더러 프로세스에 접근 하려면 [webContents.executeJavascript](web-contents.md#webcontentsexecutejavascriptcode-usergesture) 메서드를 사용하면 됩니다.
## Remote 객체

View file

@ -0,0 +1,187 @@
# session
`session` 객체는 [`BrowserWindow`](browser-window.md)의 [`webContents`](web-contents.md)의 프로퍼티입니다.
다음과 같이 `BrowserWindow` 인스턴스에서 접근할 수 있습니다:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl("http://github.com");
var session = win.webContents.session
```
## Events
### Event: 'will-download'
* `event` Event
* `item` Object
* `url` String
* `filename` String
* `mimeType` String
* `hasUserGesture` Boolean
* `webContents` [WebContents](web-contents.md)
Electron의 `webContents`에서 `item`을 다운로드할 때 발생하는 이벤트입니다.
`event.preventDefault()` 메서드를 호출하면 다운로드를 취소합니다.
```javascript
session.on('will-download', function(event, item, webContents) {
event.preventDefault();
require('request')(item.url, function(data) {
require('fs').writeFileSync('/somewhere', data);
});
});
```
## Methods
`session` 객체는 다음과 같은 메서드와 속성을 가지고 있습니다:
### `session.cookies`
`cookies` 속성은 쿠키를 조작하는 방법을 제공합니다. 예를 들어 다음과 같이 할 수 있습니다:
```javascript
var BrowserWindow = require('browser-window');
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadUrl('https://github.com');
win.webContents.on('did-finish-load', function() {
// 모든 쿠키를 가져옵니다.
win.webContents.session.cookies.get({}, function(error, cookies) {
if (error) throw error;
console.log(cookies);
});
// Url에 관련된 쿠키를 모두 가져옵니다.
win.webContents.session.cookies.get({ url : "http://www.github.com" },
function(error, cookies) {
if (error) throw error;
console.log(cookies);
});
// 지정한 쿠키 데이터를 설정합니다.
// 동일한 쿠키가 있으면 해당 쿠키를 덮어씁니다.
win.webContents.session.cookies.set(
{ url : "http://www.github.com", name : "dummy_name", value : "dummy"},
function(error, cookies) {
if (error) throw error;
console.log(cookies);
});
});
```
### `session.cookies.get(details, callback)`
`details` Object, properties:
* `url` String - `url`에 관련된 쿠키를 가져옵니다. 이 속성을 비워두면 모든 url의 쿠키를 가져옵니다.
* `name` String - 이름을 기준으로 쿠키를 필터링합니다.
* `domain` String - `domain`과 일치하는 도메인과 서브 도메인에 대한 쿠키를 가져옵니다.
* `path` String - `path`와 일치하는 경로에 대한 쿠키를 가져옵니다.
* `secure` Boolean - 보안 속성을 기준으로 쿠키를 필터링합니다.
* `session` Boolean - 세션 또는 영구 쿠키를 필터링합니다.
* `callback` Function - function(error, cookies)
* `error` Error
* `cookies` Array - `cookie` 객체의 배열, 속성은 다음과 같습니다:
* `name` String - 쿠키의 이름.
* `value` String - 쿠키의 값.
* `domain` String - 쿠키의 도메인.
* `host_only` String - 쿠키가 호스트 전용인가에 대한 여부.
* `path` String - 쿠키의 경로.
* `secure` Boolean - 쿠키가 안전한 것으로 표시되는지에 대한 여부. (일반적으로 HTTPS)
* `http_only` Boolean - 쿠키가 HttpOnly로 표시되는지에 대한 여부.
* `session` Boolean - 쿠키가 세션 쿠키 또는 만료일이 있는 영구 쿠키인지에 대한 여부.
* `expirationDate` Double - (Option) UNIX 시간으로 표시되는 쿠키의 만료일에 대한 초 단위 시간. 세션 쿠키는 지원되지 않음.
### `session.cookies.set(details, callback)`
`details` Object, properties:
* `url` String - `url`에 관련된 쿠키를 가져옵니다.
* `name` String - 쿠키의 이름입니다. 기본적으로 비워두면 생략됩니다.
* `value` String - 쿠키의 값입니다. 기본적으로 비워두면 생략됩니다.
* `domain` String - 쿠키의 도메인입니다. 기본적으로 비워두면 생략됩니다.
* `path` String - 쿠키의 경로입니다. 기본적으로 비워두면 생략됩니다.
* `secure` Boolean - 쿠키가 안전한 것으로 표시되는지에 대한 여부입니다. 기본값은 false입니다.
* `session` Boolean - 쿠키가 HttpOnly로 표시되는지에 대한 여부입니다. 기본값은 false입니다.
* `expirationDate` Double - UNIX 시간으로 표시되는 쿠키의 만료일에 대한 초 단위 시간입니다. 생략하면 쿠키는 세션 쿠키가 됩니다.
* `callback` Function - function(error)
* `error` Error
### `session.cookies.remove(details, callback)`
* `details` Object, proprties:
* `url` String - 쿠키와 관련된 URL입니다.
* `name` String - 지울 쿠키의 이름입니다.
* `callback` Function - function(error)
* `error` Error
### `session.clearCache(callback)`
* `callback` Function - 작업이 완료되면 호출됩니다.
세션의 HTTP 캐시를 비웁니다.
### `session.clearStorageData([options, ]callback)`
* `options` Object (optional), proprties:
* `origin` String - `scheme://host:port`와 같은 `window.location.origin` 규칙을 따르는 origin 문자열.
* `storages` Array - 비우려는 스토리지의 종류, 다음과 같은 타입을 포함할 수 있습니다:
`appcache`, `cookies`, `filesystem`, `indexdb`, `local storage`,
`shadercache`, `websql`, `serviceworkers`
* `quotas` Array - 비우려는 할당의 종류, 다음과 같은 타입을 포함할 수 있습니다:
`temporary`, `persistent`, `syncable`.
* `callback` Function - 작업이 완료되면 호출됩니다.
웹 스토리지의 데이터를 비웁니다.
### `session.setProxy(config, callback)`
* `config` String
* `callback` Function - 작업이 완료되면 호출됩니다.
세션에 사용할 프록시 `config`를 분석하고 프록시를 적용합니다.
```
config = scheme-proxies[";"<scheme-proxies>]
scheme-proxies = [<url-scheme>"="]<proxy-uri-list>
url-scheme = "http" | "https" | "ftp" | "socks"
proxy-uri-list = <proxy-uri>[","<proxy-uri-list>]
proxy-uri = [<proxy-scheme>"://"]<proxy-host>[":"<proxy-port>]
예시:
"http=foopy:80;ftp=foopy2" -- use HTTP proxy "foopy:80" for http://
URLs, and HTTP proxy "foopy2:80" for
ftp:// URLs.
"foopy:80" -- use HTTP proxy "foopy:80" for all URLs.
"foopy:80,bar,direct://" -- use HTTP proxy "foopy:80" for all URLs,
failing over to "bar" if "foopy:80" is
unavailable, and after that using no
proxy.
"socks4://foopy" -- use SOCKS v4 proxy "foopy:1080" for all
URLs.
"http=foopy,socks5://bar.com -- use HTTP proxy "foopy" for http URLs,
and fail over to the SOCKS5 proxy
"bar.com" if "foopy" is unavailable.
"http=foopy,direct:// -- use HTTP proxy "foopy" for http URLs,
and use no proxy if "foopy" is
unavailable.
"http=foopy;socks=foopy2 -- use HTTP proxy "foopy" for http URLs,
and use socks4://foopy2 for all other
URLs.
```
### `session.setDownloadPath(path)`
* `path` String - 다운로드 위치
다운로드 저장 위치를 지정합니다. 기본 다운로드 위치는 각 어플리케이션 데이터 디렉터리의 `Downloads` 폴더입니다.

View file

@ -1,4 +1,4 @@
# web-frame
# webFrame
`web-frame` 모듈은 현재 웹 페이지의 랜더링 상태를 설정 할 수 있도록 관련 유틸리티를 제공하는 모듈입니다.
@ -6,38 +6,43 @@
```javascript
var webFrame = require('web-frame');
webFrame.setZoomFactor(2);
```
## webFrame.setZoomFactor(factor)
## Methods
`web-frame` 모듈은 다음과 같은 메서드를 가지고 있습니다:
### `webFrame.setZoomFactor(factor)`
* `factor` Number - Zoom 값
지정한 값으로 페이지를 줌 합니다. 줌 값은 퍼센트 / 100입니다. (예시: 300% = 3.0)
지정한 값으로 페이지를 줌 합니다. 줌 값은 퍼센트를 100으로 나눈 값입니다. (예시: 300% = 3.0)
## webFrame.getZoomFactor()
### `webFrame.getZoomFactor()`
현재 줌 값을 반환합니다.
## webFrame.setZoomLevel(level)
### `webFrame.setZoomLevel(level)`
* `level` Number - Zoom level
지정한 레벨로 줌 레벨을 변경합니다. 0은 "기본 크기" 입니다.
그리고 각각 레벨 값을 올리거나 내릴 때마다 20%씩 커지거나 작아지고 기본 크기의 50%부터 300%까지 조절 제한이 있습니다.
## webFrame.getZoomLevel()
### `webFrame.getZoomLevel()`
현재 줌 레벨을 반환합니다.
## webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)
### `webFrame.setZoomLevelLimits(minimumLevel, maximumLevel)`
* `minimumLevel` Number
* `maximumLevel` Number
줌 레벨의 최대, 최소치를 지정합니다.
## webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)
### `webFrame.setSpellCheckProvider(language, autoCorrectWord, provider)`
* `language` String
* `autoCorrectWord` Boolean
@ -57,7 +62,7 @@ require('web-frame').setSpellCheckProvider("en-US", true, {
});
```
## webFrame.registerUrlSchemeAsSecure(scheme)
### `webFrame.registerUrlSchemeAsSecure(scheme)`
* `scheme` String
@ -65,10 +70,10 @@ require('web-frame').setSpellCheckProvider("en-US", true, {
보안 스킴은 혼합된 컨텐츠 경고를 발생시키지 않습니다. 예를 들어 `https``data`는 네트워크 공격자로부터 손상될 가능성이 없기 때문에 보안 스킴이라고 할 수 있습니다.
## webFrame.registerUrlSchemeAsBypassingCsp(scheme)
### `webFrame.registerUrlSchemeAsBypassingCsp(scheme)`
* `scheme` String
페이지 컨텐츠의 보안 정책에 상관없이 이 `scheme`로부터 리소스가 로드됩니다.
현재 페이지 컨텐츠의 보안 정책에 상관없이 이 `scheme`로부터 리소스가 로드됩니다.
[spellchecker]: https://github.com/atom/node-spellchecker

View file

@ -3,9 +3,9 @@
`guest` 컨텐츠(웹 페이지)를 Electron 앱 페이지에 삽입하기 위해 `webview` 태그를 사용할 수 있습니다.
게스트 컨텐츠는 `webview` 컨테이너에 담겨 대상 페이지에 삽입되고 해당 페이지에선 게스트 컨텐츠의 배치 및 렌더링 과정을 조작할 수 있습니다.
`iframe` `webview`의 차이는 어플리케이션과 프로세스가 분리되어 돌아간다는 점입니다.
그것은 모든 권한이 웹 페이지와 같지 않고 모든 앱과 임베디드(게스트) 컨텐츠간의 상호작용이 비동기로 작동한다는 것을 의미합니다.
이에 따라 임베디드 컨텐츠로부터 어플리케이션을 안전하게 유지할 수 있습니다.
`iframe`는 달리 `webview`는 어플리케이션과 분리된 프로세스에서 작동합니다.
웹 페이지와 같은 권한을 가지지 않고 앱과 임베디드(게스트) 컨텐츠간의 모든 상호작용이 비동기로 작동한다는 것을 의미합니다.
따라 임베디드 컨텐츠로부터 어플리케이션을 안전하게 유지할 수 있습니다.
## 예제
@ -40,7 +40,9 @@
## 태그 속성
### src
`webview` 태그는 다음과 같은 속성을 가지고 있습니다:
### `src`
```html
<webview src="https://www.github.com/"></webview>
@ -52,17 +54,17 @@
`src` 속성은 `data:text/plain,Hello, world!` 같은 data URL도 사용할 수 있습니다.
### autosize
### `autosize`
```html
<webview src="https://www.github.com/" autosize="on" minwidth="576" minheight="432"></webview>
```
"on" 으로 지정하면 `webview` 컨테이너는 `minwidth`, `minheight`, `maxwidth`, `maxheight`에 맞춰서 자동으로 크기를 조절합니다.
조건은 `autosize`가 활성화되어있지 않는 한 따로 영향을 주지 않습니다.
속성들은 `autosize`가 활성화되어있지 않는 한 프레임에 영향을 주지 않습니다.
`autosize`가 활성화 되어있으면 `webview` 컨테이너의 크기는 각각의 지정한 최대, 최소값에 따라 조절됩니다.
### nodeintegration
### `nodeintegration`
```html
<webview src="http://www.google.com/" nodeintegration></webview>
@ -71,7 +73,7 @@
"on"으로 지정하면 `webview` 페이지 내에서 `require``process 객체`같은 node.js API를 사용할 수 있습니다.
이를 지정하면 내부에서 로우레벨 리소스에 접근할 수 있습니다.
### plugins
### `plugins`
```html
<webview src="https://www.github.com/" plugins></webview>
@ -79,46 +81,65 @@
"on"으로 지정하면 `webview` 내부에서 브라우저 플러그인을 사용할 수 있습니다.
### preload
### `preload`
```html
<webview src="https://www.github.com/" preload="./test.js"></webview>
```
게스트 페이지가 로드되기 전에 실행할 스크립트를 지정합니다.
페이지가 로드되기 전에 실행할 스크립트를 지정합니다.
스크립트 URL은 `file:` 또는 `asar:` 프로토콜 중 하나를 반드시 사용해야 합니다.
왜냐하면 `require`를 사용해 게스트 페이지 내에서 스크립트를 로드하기 때문입니다.
왜냐하면 페이지 내에서 `require`를 사용하여 스크립트를 로드하기 때문입니다.
게스트 페이지가 nodeintegration을 활성화 하지 않았어도 지정된 스크립트는 정상적으로 돌아갑니다.
페이지가 nodeintegration을 활성화 하지 않아도 지정한 스크립트는 정상적으로 작동합니다.
하지만 스크립트 내에서 사용할 수 있는 global 객체는 스크립트 작동이 끝나면 삭제됩니다.
### httpreferrer
### `httpreferrer`
```html
<webview src="https://www.github.com/" httpreferrer="http://cheng.guru"></webview>
```
게스트 페이지의 referrer URL을 설정합니다.
페이지의 referrer URL을 설정합니다.
### useragent
### `useragent`
```html
<webview src="https://www.github.com/" useragent="Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"></webview>
```
게스트 페이지의 `User-Agent`를 설정합니다. 페이지가 로드된 후엔 `setUserAgent` 메소드를 사용해서 변경할 수 있습니다.
페이지의 `User-Agent`를 설정합니다. 페이지가 로드된 후엔 `setUserAgent` 메소드를 사용해서 변경할 수 있습니다.
### disablewebsecurity
### `disablewebsecurity`
```html
<webview src="https://www.github.com/" disablewebsecurity></webview>
```
"on"으로 지정하면 게스트 페이지의 웹 보안을 해제합니다.
"on"으로 지정하면 페이지의 웹 보안을 해제합니다.
## API
### `partition`
webview 메서드는 페이지 로드가 끝난 뒤에만 사용할 수 있습니다.
```html
<webview src="https://github.com" partition="persist:github"></webview>
<webview src="http://electron.atom.io" partition="electron"></webview>
```
페이지에서 사용하는 세션을 설정합니다.
만약 `partition` 속성이 `persist:` 접두사를 시작하면 같은 `partition` 속성을 가진 앱 내 모든 페이지가 공유하는 영구 세션을 사용합니다.
`persist:` 접두사가 없을 경우 페이지는 인 메모리 세션을 사용합니다.
동일한 `partition`을 지정하여 다중 페이지에서 동일한 세션을 공유할 수 있도록 할 수 있습니다.
만약 `partition`이 지정되지 않으면 앱의 기본 세션을 사용합니다.
이 값은 첫 탐색 이전에만 지정할 수 있습니다.
즉. 작동중인 랜더러 프로세스의 세션은 변경할 수 없습니다.
이후 이 값을 바꾸려고 시도하면 DOM 예외를 발생시킵니다.
## Methods
`webview` 태그는 다음과 같은 메서드를 가지고 있습니다:
**참고:** <webview> 태그 객체의 메서드는 페이지 로드가 끝난 뒤에만 사용할 수 있습니다.
**예제**
```javascript
@ -127,229 +148,241 @@ webview.addEventListener("dom-ready", function() {
});
```
### `<webview>`.getUrl()
### `<webview>.getUrl()`
게스트 페이지의 URL을 반환합니다.
페이지의 URL을 반환합니다.
### `<webview>`.getTitle()
### `<webview>.getTitle()`
게스트 페이지의 제목을 반환합니다.
페이지의 제목을 반환합니다.
### `<webview>`.isLoading()
### `<webview>.isLoading()`
페이지가 아직 리소스를 로딩하고 있는지 확인합니다.
페이지가 아직 리소스를 로딩하고 있는지 확인합니다. 불린 값을 반환합니다.
### `<webview>`.isWaitingForResponse()
### `<webview>.isWaitingForResponse()`
게스트 페이지가 메인 리소스의 첫 응답을 기다리고 있는지 확인합니다.
페이지가 메인 리소스의 첫 응답을 기다리고 있는지 확인합니다. 불린 값을 반환합니다.
### `<webview>`.stop()
### `<webview>.stop()`
모든 탐색을 취소합니다.
### `<webview>`.reload()
### `<webview>.reload()`
페이지를 새로고침합니다.
### `<webview>`.reloadIgnoringCache()
### `<webview>.reloadIgnoringCache()`
캐시를 무시하고 페이지를 새로고침합니다.
### `<webview>`.canGoBack()
### `<webview>.canGoBack()`
페이지 히스토리를 한 칸 뒤로 가기를 할 수 있는지 확인합니다.
페이지 히스토리를 한 칸 뒤로 가기를 할 수 있는지 확인합니다. 불린 값을 반환합니다.
### `<webview>`.canGoForward()
### `<webview>.canGoForward()`
페이지 히스토리를 한 칸 앞으로 가기를 할 수 있는지 확인합니다.
페이지 히스토리를 한 칸 앞으로 가기를 할 수 있는지 확인합니다. 불린 값을 반환합니다.
### `<webview>`.canGoToOffset(offset)
### `<webview>.canGoToOffset(offset)`
* `offset` Integer
페이지 히스토리를 `offset` 만큼 이동할 수 있는지 확인합니다.
페이지 히스토리를 `offset` 만큼 이동할 수 있는지 확인합니다. 불린값을 반환합니다.
### `<webview>`.clearHistory()
### `<webview>.clearHistory()`
탐색 히스토리를 비웁니다.
### `<webview>`.goBack()
### `<webview>.goBack()`
페이지 뒤로 가기를 실행합니다.
### `<webview>`.goForward()
### `<webview>.goForward()`
페이지 앞으로 가기를 실행합니다.
### `<webview>`.goToIndex(index)
### `<webview>.goToIndex(index)`
* `index` Integer
페이지를 지정한 `index`로 이동합니다.
### `<webview>`.goToOffset(offset)
### `<webview>.goToOffset(offset)`
* `offset` Integer
현재 페이지로 부터 `offset` 만큼 이동합니다.
페이지로부터 `offset` 만큼 이동합니다.
### `<webview>`.isCrashed()
### `<webview>.isCrashed()`
랜더러 프로세스가 크래시 됬는지 확인합니다.
### `<webview>`.setUserAgent(userAgent)
### `<webview>.setUserAgent(userAgent)`
* `userAgent` String
`User-Agent`를 지정합니다.
### `<webview>`.getUserAgent()
### `<webview>.getUserAgent()`
현재 페이지의 `User-Agent` 문자열을 가져옵니다.
페이지의 `User-Agent 문자열`을 가져옵니다.
### `<webview>`.insertCSS(css)
### `<webview>.insertCSS(css)`
* `css` String
게스트 페이지에 CSS를 삽입합니다.
페이지에 CSS를 삽입합니다.
### `<webview>`.executeJavaScript(code[, userGesture])
### `<webview>.executeJavaScript(code[, userGesture])`
* `code` String
* `userGesture` Boolean
게스트 페이지에서 자바스크립트 `code`를 실행합니다.
페이지에서 자바스크립트 `code`를 실행합니다.
`userGesture``true`로 설정되어 있으면 `requestFullScreen` HTML API 같이
유저의 승인이 필요한 API를 유저의 승인을 무시하고 개발자가 API를 직접 사용할 수 있습니다.
만약 `userGesture``true`로 설정되어 있으면 페이지에 유저 제스쳐 컨텍스트를 만듭니다.
이 옵션을 활성화 시키면 `requestFullScreen`와 같은 HTML API에서 유저의 승인을 무시하고 개발자가 API를 바로 사용할 수 있도록 허용합니다.
역주: 기본적으로 브라우저에선 전체화면, 웹캠, 파일 열기등의 API를 사용하려면 유저의 승인(이벤트)이 필요합니다.
### `<webview>`.openDevTools()
### `<webview>.openDevTools()`
게스트 페이지에 대한 개발자 툴을 엽니다.
페이지에 대한 개발자 콘솔을 엽니다.
### `<webview>`.closeDevTools()
### `<webview>.closeDevTools()`
게스트 페이지에 대한 개발자 툴을 닫습니다.
페이지에 대한 개발자 콘솔을 닫습니다.
### `<webview>`.isDevToolsOpened()
### `<webview>.isDevToolsOpened()`
게스트 페이지에 대한 개발자 툴이 열려있는지 확인합니다.
페이지에 대한 개발자 콘솔이 열려있는지 확인합니다. 불린 값을 반환합니다.
### `<webview>`.inspectElement(x, y)
### `<webview>.inspectElement(x, y)`
* `x` Integer
* `y` Integer
(`x`, `y`) 위치에 있는 엘리먼트를 inspect합니다.
### `<webview>`.inspectServiceWorker()
### `<webview>.inspectServiceWorker()`
Service worker에 대한 개발자 을 엽니다.
Service worker에 대한 개발자 콘솔을 엽니다.
### `<webview>`.undo()
### `<webview>.undo()`
페이지에서 실행 취소 커맨드를 실행합니다.
### `<webview>`.redo()
### `<webview>.redo()`
페이지에서 다시 실행 커맨드를 실행합니다.
### `<webview>`.cut()
### `<webview>.cut()`
페이지에서 잘라내기 커맨드를 실행합니다.
### `<webview>`.copy()
### `<webview>.copy()`
페이지에서 복사 커맨드를 실행합니다.
### `<webview>`.paste()
### `<webview>.paste()`
페이지에서 붙여넣기 커맨드를 실행합니다.
### `<webview>`.pasteAndMatchStyle()
### `<webview>.pasteAndMatchStyle()`
페이지에서 `pasteAndMatchStyle` 편집 커맨드를 실행합니다.
### `<webview>`.delete()
### `<webview>.delete()`
페이지에서 삭제 커맨드를 실행합니다.
### `<webview>`.selectAll()
### `<webview>.selectAll()`
페이지에서 전체 선택 커맨드를 실행합니다.
### `<webview>`.unselect()
### `<webview>.unselect()`
페이지에서 `unselect` 커맨드를 실행합니다.
### `<webview>`.replace(text)
### `<webview>.replace(text)`
* `text` String
페이지에서 `replace` 커맨드를 실행합니다.
### `<webview>`.replaceMisspelling(text)
### `<webview>.replaceMisspelling(text)`
* `text` String
페이지에서 `replaceMisspelling` 커맨드를 실행합니다.
### `<webview>`.print([options])
### `<webview>.print([options])`
Webview 페이지를 인쇄합니다. `webContents.print([options])` 메서드와 같습니다.
### `<webview>`.printToPDF(options, callback)
### `<webview>.printToPDF(options, callback)`
Webview 페이지를 PDF 형식으로 인쇄합니다. `webContents.printToPDF(options, callback)` 메서드와 같습니다.
### `<webview>`.send(channel[, args...])
### `<webview>.send(channel[, args...])`
* `channel` String
* `args` (optional)
`channel`을 통해 게스트 페이지에 `args...` 비동기 메시지를 보냅니다.
게스트 페이지에선 `ipc` 모듈의 `channel` 이벤트를 사용하면 이 메시지를 받을 수 있습니다.
`channel`을 통해 페이지에 `args` 비동기 메시지를 보냅니다.
페이지에선 `ipc` 모듈의 `channel` 이벤트를 사용하면 이 메시지를 받을 수 있습니다.
예제는 [WebContents.send](browser-window.md#webcontentssendchannel-args)를 참고하세요.
예제는 [WebContents.send](web-contents.md#webcontentssendchannel-args)를 참고하세요.
## DOM 이벤트
### load-commit
`webview` 태그는 다음과 같은 DOM 이벤트를 가지고 있습니다:
### Event: 'load-commit'
Returns:
* `url` String
* `isMainFrame` Boolean
Fired when a load has committed. This includes navigation within the current
document as well as subframe document-level loads, but does not include
asynchronous resource loads.
로드가 시작됬을 때 발생하는 이벤트입니다.
이 이벤트는 현재 문서내의 탐색뿐만 아니라 서브 프레임 문서 레벨의 로드도 포함됩니다.
하지만 비동기 리소스 로드는 포함되지 않습니다.
### did-finish-load
### Event: 'did-finish-load'
탐색이 끝나면 발생하는 이벤트입니다. 브라우저 탭의 스피너가 멈추고 `onload` 이벤트가 발생 때를 생각하면 됩니다.
탐색이 끝나면 발생하는 이벤트입니다. 브라우저 탭의 스피너가 멈추고 `onload` 이벤트가 발생 때를 생각하면 됩니다.
### did-fail-load
### Event: 'did-fail-load'
Returns:
* `errorCode` Integer
* `errorDescription` String
* `validatedUrl` String
`did-finish-load`와 비슷합니다. 하지만 이 이벤트는 `window.stop()`과 같은 무언가로 인해 로드에 실패했을 때 발생하는 이벤트입니다.
### did-frame-finish-load
### Event: 'did-frame-finish-load'
Returns:
* `isMainFrame` Boolean
프레임의 탐색이 끝나면 발생하는 이벤트입니다.
### did-start-loading
### Event: 'did-start-loading'
브라우저 탭의 스피너가 돌기 시작할 때 처럼 페이지의 로드가 시작될 때 발생하는 이벤트입니다.
### did-stop-loading
### Event: 'did-stop-loading'
브라우저 탭의 스피너가 멈출 때 처럼 페이지의 로드가 끝나면 발생하는 이벤트입니다.
### did-get-response-details
### Event: 'did-get-response-details'
Returns:
* `status` Boolean
* `newUrl` String
@ -362,7 +395,9 @@ asynchronous resource loads.
요청한 리소스에 관해 자세한 내용을 알 수 있을 때 발생하는 이벤트입니다.
`status`는 리소스를 다운로드할 소켓 커낵션을 나타냅니다.
### did-get-redirect-request
### Event: 'did-get-redirect-request'
Returns:
* `oldUrl` String
* `newUrl` String
@ -370,32 +405,38 @@ asynchronous resource loads.
리소스를 요청하고 받는 도중에 리다이렉트가 생기면 발생하는 이벤트입니다.
### dom-ready
### Event: 'dom-ready'
현재 프레임 문서의 로드가 끝나면 발생하는 이벤트입니다.
프레임 문서의 로드가 끝나면 발생하는 이벤트입니다.
### page-title-set
### Event: 'page-title-set'
Returns:
* `title` String
* `explicitSet` Boolean
탐색하는 동안에 페이지의 제목이 설정되면 발생하는 이벤트입니다. `explicitSet`는 파일 URL에서 종합(synthesised)된 제목인 경우 false로 표시됩니다.
### page-favicon-updated
### Event: 'page-favicon-updated'
* `favicons` Array - Array of Urls
Returns:
* `favicons` Array - URL 배열
페이지가 favicon URL을 받았을 때 발생하는 이벤트입니다.
### enter-html-full-screen
### Event: 'enter-html-full-screen'
페이지가 HTML API에 의해 전체 화면 모드에 돌입했을 때 발생하는 이벤트입니다.
### leave-html-full-screen
### Event: 'leave-html-full-screen'
페이지의 전체 화면 모드가 해제됬을 때 발생하는 이벤트입니다.
### console-message
### Event: 'console-message'
Returns:
* `level` Integer
* `message` String
@ -412,14 +453,16 @@ webview.addEventListener('console-message', function(e) {
});
```
### new-window
### Event: 'new-window'
Returns:
* `url` String
* `frameName` String
* `disposition` String - Can be `default`, `foreground-tab`, `background-tab`,
`new-window` and `other`
게스트 페이지가 새로운 브라우저 창을 생성할 때 발생하는 이벤트입니다.
페이지가 새로운 브라우저 창을 생성할 때 발생하는 이벤트입니다.
다음 예제 코드는 새 URL을 시스템의 기본 브라우저로 여는 코드입니다.
@ -429,11 +472,11 @@ webview.addEventListener('new-window', function(e) {
});
```
### close
### Event: 'close'
게스트 페이지가 자체적으로 닫힐 때 발생하는 이벤트입니다.
페이지가 자체적으로 닫힐 때 발생하는 이벤트입니다.
다음 예제 코드는 게스트 페이지가 자체적으로 닫힐 때 `webview``about:blank` 페이지로 이동시키는 예제입니다.
다음 예제 코드는 페이지가 자체적으로 닫힐 때 `webview``about:blank` 페이지로 이동시키는 예제입니다.
```javascript
webview.addEventListener('close', function() {
@ -441,7 +484,9 @@ webview.addEventListener('close', function() {
});
```
### ipc-message
### Event: 'ipc-message'
Returns:
* `channel` String
* `args` Array
@ -467,21 +512,23 @@ ipc.on('ping', function() {
});
```
### crashed
### Event: 'crashed'
랜더러 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### gpu-crashed
### Event: 'gpu-crashed'
GPU 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### plugin-crashed
### Event: 'plugin-crashed'
Returns:
* `name` String
* `version` String
플러그인 프로세스가 크래시 되었을 때 발생하는 이벤트입니다.
### destroyed
### Event: 'destroyed'
WebContents가 파괴될 때 발생하는 이벤트입니다.

View file

@ -1,20 +1,20 @@
# `window.open` 메서드
# `window.open` 함수
`window.open` 메서드가 호출되면 새 창을 생성하고 `url` 페이지를 불러옵니다.
`window.open` 함수가 호출되면 새 창을 생성하고 `url` 페이지를 불러옵니다.
이 창은 지정한 `url`을 로드하여 만들어진 `BrowserWindow`의 새 인스턴스이며 본래 창 객체 대신 페이지의 컨트롤이 제한된 프록시 객체를 반환합니다.
프록시 객체는 브라우저의 웹 페이지 창과 호환될 수 있도록 일부 제한된 표준 기능만 가지고 있습니다.
창의 모든 컨트롤을 가지려면 `BrowserWindow`를 직접 생성하여 작업해야 합니다.
창의 모든 컨트롤 권한을 가지려면 `BrowserWindow`를 직접 생성해서 사용해야 합니다.
## window.open(url, [frameName[, features]])
### `window.open(url[, frameName][, features])`
* `url` String
* `frameName` String
* `features` String
* `frameName` String (optional)
* `features` String (optional)
`BrowserWindowProxy` 클래스의 객체를 반환하는 새로운 윈도우를 생성합니다.
## window.opener.postMessage(message, targetOrigin)
### `window.opener.postMessage(message, targetOrigin)`
* `message` String
* `targetOrigin` String
@ -23,31 +23,31 @@
## Class: BrowserWindowProxy
### BrowserWindowProxy.blur()
### `BrowserWindowProxy.blur()`
자식 윈도우의 포커스를 해제합니다.
### BrowserWindowProxy.close()
### `BrowserWindowProxy.close()`
자식 윈도우를 강제로 닫습니다. unload 이벤트가 발생하지 않습니다.
Forcefully closes the child window without calling its unload event.
### BrowserWindowProxy.closed
### `BrowserWindowProxy.closed`
자식 윈도우가 닫히면 true로 설정됩니다.
### BrowserWindowProxy.eval(code)
### `BrowserWindowProxy.eval(code)`
* `code` String
자식 윈도우에서 특정 스크립트를 실행합니다.
### BrowserWindowProxy.focus()
### `BrowserWindowProxy.focus()`
자식 윈도우에 포커스를 맞춥니다. (창을 맨 앞으로 가져옵니다)
### BrowserWindowProxy.postMessage(message, targetOrigin)
### `BrowserWindowProxy.postMessage(message, targetOrigin)`
* `message` String
* `targetOrigin` String

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