public void InitilaizeSession(string contentsPath) { var prefs = new WebPreferences(); var session = WebCore.CreateWebSession(prefs); session.AddDataSource("content", new Awesomium.Core.Data.DirectoryDataSource(contentsPath)); htmlRenderer.WebSession = session; }
private static void AllowInsecureContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MainWindow owner = (MainWindow)d; bool value = (bool)e.NewValue; WebPreferences currentPrefs = WebPreferences; currentPrefs.AllowInsecureContent = value; Settings.Default.WebPreferences = currentPrefs; owner.CoerceValue(MainWindow.RestartProperty); }
private static void ShowImagesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MainWindow owner = (MainWindow)d; bool value = (bool)e.NewValue; WebPreferences currentPrefs = WebPreferences; currentPrefs.LoadImagesAutomatically = value; Settings.Default.WebPreferences = currentPrefs; owner.CoerceValue(MainWindow.RestartProperty); }
private static void FileAccessFromFileURLChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MainWindow owner = (MainWindow)d; bool value = (bool)e.NewValue; WebPreferences currentPrefs = WebPreferences; currentPrefs.FileAccessFromFileURL = value; Settings.Default.WebPreferences = currentPrefs; owner.CoerceValue(MainWindow.RestartProperty); }
public async void Bootstrap() { WebPreferences wp = new WebPreferences(); wp.NodeIntegration = false; BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions { WebPreferences = wp }; await Electron.WindowManager.CreateWindowAsync(browserWindowOptions); }
public Browser(BrowserSettings browserSettings) { _browserSettings = browserSettings; var preferences = new WebPreferences(); if (browserSettings.Proxy?.Length > 0) { preferences.ProxyConfig = browserSettings.Proxy; } WebCore.DoWork(() => { _session = WebCore.CreateWebSession(preferences); return default(int); }); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { DatabaseManager.SqliteFilename = "asa.sqlite"; DatabaseManager.Setup(); Logger.Setup(); Telemetry.Setup(Gui: true); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); WebPreferences wp = new WebPreferences(); wp.NodeIntegration = false; wp.ContextIsolation = true; BrowserWindowOptions browserWindowOptions = new BrowserWindowOptions { #if DEBUG AutoHideMenuBar = false, #else AutoHideMenuBar = true, #endif Width = 1200, Height = 1000, Resizable = true, Center = true, Title = string.Format("Attack Surface Analyzer {0}", Helpers.GetVersionString()), WebPreferences = wp }; Task.Run(async() => { await Electron.WindowManager.CreateWindowAsync(browserWindowOptions); }); }
public void Initialize(GraphicsDevice device, int renderTargetWidth, int renderTargetHeight, string basePath, string customCss = "") { mBasePath = basePath; //OnLoadCompleted = new OnLoadCompletedDelegate(); //WebCore.Initialize(new WebCoreConfig() { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" }); //WebCore.Initialize(new WebConfig() { CustomCSS = customCSS, SaveCacheAndCookies = true }); //1.7 //WebCore.Initialize(new WebCoreConfig() { CustomCSS = customCSS, SaveCacheAndCookies = true }); var webConfig = new WebConfig { LogPath = Environment.CurrentDirectory, LogLevel = LogLevel.Verbose }; WebCore.Initialize(webConfig); var webPreferences = new WebPreferences { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" }; WebSession = WebCore.CreateWebSession(webPreferences); if (mLogger != null) { mLogger.Info("WEBCORE initialized."); } WebTexture = new Texture2D(device, renderTargetWidth, renderTargetHeight); if (mLogger != null) { mLogger.Info("Rendertarget created."); } WebView = WebCore.CreateWebView(renderTargetWidth, renderTargetHeight, WebSession); //LoadingFrameComplete still seems to take an //inordinate amout of time with local files... //SOMETIMES. //As long as you haven't navigated to an online //page and back it is instant. Odd. WebView.DocumentReady += OnDocumentReadyInternal; WebView.LoadingFrameComplete += OnLoadingFrameCompleteInternal; if (mLogger != null) { mLogger.Info("WebView created."); } WebView.IsTransparent = true; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, sc2dsstatsContext context, ILoggerFactory loggerFactory) { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; ApplicationLogging.LoggerFactory = loggerFactory; context.Database.Migrate(); var path = ElectronService.GetPath().GetAwaiter().GetResult(); DSData.Init(path); NameService.Init(context, path).GetAwaiter().GetResult(); app.UseResponseCompression(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); endpoints.MapFallbackToPage("/_Host"); }); WebPreferences wp = new WebPreferences(); wp.NodeIntegration = false; Task.Run(async() => await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions() { AutoHideMenuBar = true, Width = 1920, Height = 1080, X = 0, Y = 0, WebPreferences = wp })); }
public MainWindow(string[] args) { InitializeComponent(); // Load theme. ThemeManager.ChangeTheme(Application.Current, ThemeManager.DefaultAccents[Settings.Default.CurrentAccent], (Theme)Settings.Default.CurrentTheme); this.MetroDialogOptions.ColorScheme = MahApps.Metro.Controls.Dialogs.MetroDialogColorScheme.Accented; // Keep this for comparison. // If we change preferences, we need to restart // the application for the changes to be applied. initialPreferences = Settings.Default.WebPreferences; // Keep this. We will use it when we load. initialUrls = args; // Initialize collections. tabViews = new TabViewCollection(); this.SetValue(MainWindow.ViewsPropertyKey, tabViews); this.SetValue(MainWindow.DownloadsPropertyKey, WebCore.Downloads); this.SetValue(MainWindow.AccentsPropertyKey, ThemeManager.DefaultAccents.Select( a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush }).ToList()); // Assign event handlers. this.Loaded += OnLoaded; // Assign command handlers. this.CommandBindings.Add(new CommandBinding(MainWindow.OpenInTab, OnOpenTab, CanOpen)); this.CommandBindings.Add(new CommandBinding(MainWindow.OpenInWindow, OnOpenWindow, CanOpen)); this.CommandBindings.Add(new CommandBinding(MainWindow.OpenSource, OnOpenSource, CanOpenSource)); this.CommandBindings.Add(new CommandBinding(MainWindow.CloseTab, OnCloseTab)); this.CommandBindings.Add(new CommandBinding(MainWindow.NewTab, OnNewTab)); this.CommandBindings.Add(new CommandBinding(MainWindow.ShowDownloads, OnShowDownloads)); this.CommandBindings.Add(new CommandBinding(MainWindow.ShowSettings, OnShowSettings)); this.CommandBindings.Add(new CommandBinding(MainWindow.CloseSettings, OnCloseSettings)); this.CommandBindings.Add(new CommandBinding(MainWindow.UpdateHomeURL, OnUpdateHomeURL)); this.CommandBindings.Add(new CommandBinding(MainWindow.Search, OnSearch)); this.CommandBindings.Add(new CommandBinding(MainWindow.RestartApplication, OnRestartApplication)); this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, OnClose)); // Perform lazy initialization of the WebCore. this.InitializeCore(); }
private static async void ElectronBootstrap() { var wp = new WebPreferences { NodeIntegration = false }; var browserWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions { WebPreferences = wp, Width = 1920, Height = 1080, Show = false }); browserWindow.OnReadyToShow += () => browserWindow.Show(); browserWindow.SetTitle("ElectronALPR"); }
public void Ready() { // Write a message to the Console Console.WriteLine("Welcome to Bridge.NET"); WebPreferences wp = new WebPreferences() { sandbox = true, contextIsolation = true, nodeIntegration = false }; if (USE_SPIDER) { wp.preload = @"bin\Debug\bridge\spider.js"; } MainWindow = new BrowserWindow(new BrowserWindowConstructorOptions() { width = 1280, height = 600, title = "JsTracer", skipTaskbar = false, webPreferences = wp }); MainWindow.webContents.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"); //$NOTE: don't enable this, or it will detach debugger from our end /*if (!MainWindow.webContents.isDevToolsOpened()) { * MainWindow.webContents.openDevTools(); * }*/ MainWindow.webContents.once(lit.did_start_loading, () => { //$TODO: Do we need to clear scripts/breakpoints when changing page? scripts.Clear(); Debug(); }); MainWindow.loadURL(PAGE_URL); MainWindow.webContents.on(lit.crashed, (ev, input) => { throw new Exception(ev.ToString()); }); }
public Form1() { WebCore.Initialize(new WebConfig()); WebPreferences wp = new WebPreferences(); wp.AcceptLanguage = "ru-ru"; wp.ProxyConfig = "5.1.50.138:8080"; WebSession ws = WebCore.CreateWebSession(wp); InitializeComponent(); webControl1.WebSession = ws; /* * var ws = WebCore.CreateWebSession(new WebPreferences() { ProxyConfig = "255.255.255:8080" }); * webControl1 = new Awesomium.Windows.Forms.WebControl() { WebSession = ws }; * this.Controls.Add(webControl1);*/ }
public void Initialize(GraphicsDevice device, int renderTargetWidth, int renderTargetHeight, string basePath, string customCss = "") { mBasePath = basePath; //OnLoadCompleted = new OnLoadCompletedDelegate(); //WebCore.Initialize(new WebCoreConfig() { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" }); //WebCore.Initialize(new WebConfig() { CustomCSS = customCSS, SaveCacheAndCookies = true }); //1.7 //WebCore.Initialize(new WebCoreConfig() { CustomCSS = customCSS, SaveCacheAndCookies = true }); var webConfig = new WebConfig { LogPath = Environment.CurrentDirectory, LogLevel = LogLevel.Verbose }; WebCore.Initialize(webConfig); var webPreferences = new WebPreferences { CustomCSS = "::-webkit-scrollbar { visibility: hidden; }" }; WebSession = WebCore.CreateWebSession(webPreferences); if (mLogger != null) mLogger.Info("WEBCORE initialized."); WebTexture = new Texture2D(device, renderTargetWidth, renderTargetHeight); if (mLogger != null) mLogger.Info("Rendertarget created."); WebView = WebCore.CreateWebView(renderTargetWidth, renderTargetHeight, WebSession); //LoadingFrameComplete still seems to take an //inordinate amout of time with local files... //SOMETIMES. //As long as you haven't navigated to an online //page and back it is instant. Odd. WebView.DocumentReady += OnDocumentReadyInternal; WebView.LoadingFrameComplete += OnLoadingFrameCompleteInternal; if (mLogger != null) mLogger.Info("WebView created."); WebView.IsTransparent = true; }
public BtcBot(MainForm form, string _user, string _pass, string _proxy, string _address, CookieContainer _cookie, int _timeout, int _interval) { Pos = -1; mainThread.WorkerSupportsCancellation = true; mainThread.DoWork += new DoWorkEventHandler(mainThread_DoWork); mainThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(mainThread_Complete); loginThread.WorkerSupportsCancellation = true; loginThread.DoWork += new DoWorkEventHandler(loginThread_DoWork); adsThread.WorkerSupportsCancellation = true; adsThread.DoWork += new DoWorkEventHandler(adsThread_DoWork); adsThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(adsThread_Complete); wdrawThread.WorkerSupportsCancellation = true; wdrawThread.DoWork += new DoWorkEventHandler(wdrawThread_DoWork); // wdrawThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(wdrawThread_Complete); Username = _user; Password = _pass; Proxy = _proxy; Address = _address; waitTimeout = _timeout; Interval = _interval; Cookie = _cookie; var prefs = new WebPreferences(); if (Proxy != "None") { prefs.ProxyConfig = Proxy; } prefs.WebAudio = false; prefs.Plugins = false; webBrowser.WebSession = WebCore.CreateWebSession(prefs); webBrowser.ViewType = WebViewType.Offscreen; form.Controls.Add(webBrowser); }
public async void SetupElectron() { WebPreferences wp = new WebPreferences { WebviewTag = true, }; BuildMenu(); lastPing = DateTime.Now; browserWindow = await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions { Width = int.Parse(Settings.GetSetting("BrowserWidth")), Height = int.Parse(Settings.GetSetting("BrowserHeight")), WebPreferences = wp, Show = false, AlwaysOnTop = true, }); await browserWindow.WebContents.Session.ClearCacheAsync();//clear cache so local CSS and Js files are always up to date Electron.GlobalShortcut.UnregisterAll(); SetToggleOverlayAccelerator(Settings.GetSetting("ToggleOverlay")); SetResetPasswordAccelerator(Settings.GetSetting("ResetPassword")); browserWindow.OnClosed += () => { Electron.GlobalShortcut.UnregisterAll(); Electron.App.Quit(); }; browserWindow.OnResize += BrowserWindow_OnResize; browserWindow.OnReadyToShow += BrowserWindow_OnReadyToShow1; Electron.IpcMain.On("Ping", (obj) => { lastPing = DateTime.Now; }); Electron.IpcMain.On("SetRealmEyeStyle", (style) => { Settings.SetSetting("RealmEyeStyle", (string)style); }); Electron.IpcMain.On("SetSettingsStyle", (style) => { Settings.SetSetting("SettingsStyle", (string)style); }); Electron.IpcMain.On("SetToggleOverlay", (accelerators) => { SetToggleOverlayAccelerator((string)accelerators); }); Electron.IpcMain.On("SetResetPassword", (accelerators) => { SetResetPasswordAccelerator((string)accelerators); }); Electron.IpcMain.On("SetChatMessageMethod", (ChatMessageMethod) => { Settings.SetSetting("ChatMessageMethod", (string)ChatMessageMethod); }); Electron.IpcMain.On("SendInGameMessage", (args) => { dynamic expand = args; ChatMessage($"/tell {expand.username} {expand.message}"); }); }
/// <summary> /// Navigates to the specified Url. /// </summary> /// <param name="url">Url to navigate to.</param> public void Navigate(string url) { if (loaded) { // prepend with "http://" if url not well formed if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { url = "http://" + url; } activationContext.Activate(); WebMutableURLRequest request = new WebMutableURLRequestClass(); request.initWithURL(url, _WebURLRequestCachePolicy.WebURLRequestReloadIgnoringCacheData, 60); request.setHTTPMethod("GET"); //use basic authentication if username and password are supplied. if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password)) { request.setValue("Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes( string.Format("{0}:{1}", UserName, Password))), "Authorization"); } webView.mainFrame().loadRequest((WebURLRequest)request); WebPreferences p = webView.preferences(); p.setMinimumFontSize(16); p.setFontSmoothing(FontSmoothingType.FontSmoothingTypeWindows); activationContext.Deactivate(); } else { initialUrl = url.Length == 0 ? null : new Uri(url); } }
private void InitializeBrowser() { WebConfig webConfig = WebConfig.Default; if (!WebCore.IsInitialized) { WebCore.Initialize(webConfig, true); } WebPreferences webPreferences = WebPreferences.Default; //webPreferences.ProxyConfig = "198.1.99.26:3128"; //webPreferences.CustomCSS = "body { overflow:hidden; }"; //webPreferences.WebSecurity = false; webPreferences.DefaultEncoding = "UTF-8"; webSession = WebCore.CreateWebSession(webPreferences); webView = WebCore.CreateWebView(1366, 768, webSession, WebViewType.Offscreen); webView.LoadingFrameComplete += WebView_LoadingFrameComplete; // Load a URL. webView.Source = new Uri("https://translate.google.com/"); while (!isDomReady) { Thread.Sleep(100); // A Console application does not have a synchronization // context, thus auto-update won't be enabled on WebCore. // We need to manually call Update here. WebCore.Update(); } //BitmapSurface surface = (BitmapSurface)webView.Surface; //surface.SaveToPNG("result.png", true); //System.Diagnostics.Process.Start("result.png"); }
private static string Tr(string textToTranslate, string fromLng, string toLng) { string html = string.Empty; bool finishedLoading = false; WebConfig config = WebConfig.Default; if (!WebCore.IsInitialized) { WebCore.Initialize(config); } Uri url = new Uri(String.Format("https://translate.google.com/#view=home&op=translate&sl={0}&tl={1}&text={2}", fromLng, toLng, textToTranslate)); WebPreferences prefs = WebPreferences.Default; //prefs.ProxyConfig = "198.1.99.26:3128"; using (WebSession session = WebCore.CreateWebSession(prefs)) { // WebView implements IDisposable. Here we demonstrate // wrapping it in a using statement. using (WebView webView = WebCore.CreateWebView(1366, 768, session, WebViewType.Offscreen)) { // Load a URL. webView.Source = url; //WebCore.Run(); // This event is fired when a frame in the // page finished loading. webView.LoadingFrameComplete += (s, e) => { // The main frame usually finishes loading last for a given page load. if (e.IsMainFrame) { finishedLoading = true; } }; while (!finishedLoading) { Thread.Sleep(100); // A Console application does not have a synchronization // context, thus auto-update won't be enabled on WebCore. // We need to manually call Update here. WebCore.Update(); } html = webView.HTML; int substringIndex = html.IndexOf("<span title=\"\">"); if (substringIndex == -1) { return(null); } html = html.Substring(substringIndex + 15); substringIndex = html.IndexOf("</span></span>"); if (substringIndex == -1) { return(null); } html = html.Remove(substringIndex); html = html.Replace("<br>", "\r\n"); html = html.Replace("</span>", ""); html = html.Replace("<span title=\"\">", ""); } // Destroy and dispose the view. } // Release and dispose the session. // Shut down Awesomium before exiting. //WebCore.Shutdown(); return(html); }
public void AddTab(string u = "") { QTabPage tbp = new QTabPage(); tbp.Text = "No Title"; WebDisplay view = new WebDisplay(); WebPreferences prefs = new WebPreferences(); prefs.UniversalAccessFromFileUrlsAllowed = false; prefs.WebGLDisabled = false; view.Preferences = prefs; view.InitializeEngine("about:blank"); view.Focus(); tbp.Controls.Add(view); TabC.Controls.Add(tbp); TabC.ActiveTabPage = tbp; view.Anchor = (AnchorStyles)(AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top); if (panel1.Visible == false) { view.Size = new System.Drawing.Size(tbp.Width, tbp.Height); view.Location = new Point(0, 0); } else { view.Size = new System.Drawing.Size(tbp.Width, tbp.Height - panel1.Height); view.Location = new Point(0, panel1.Height); } //ShowNavBar(view); if (!string.IsNullOrEmpty(u)) if (u.Contains("\\") && !u.StartsWith("file://")) view.OpenDocument(); else if (IsURL(u)) view.Navigate(u); else Search(u); OnTabChangedTriggered(); DoOverflow(); AddEvents(view); FaviconCollection.Add(view, Properties.Resources.favicons); view.Disposed += delegate(object sender, EventArgs e) { FaviconCollection.Remove((WebDisplay)sender); }; //AddContextMenus(view); btnaddtab.Left = tbp.TabButton.Left + tbp.TabButton.Width - 5; }
public static bool GetDeveloperExtrasEnabled(this WebPreferences This) { return(global::WebKit.Messaging.bool_objc_msgSend(This.Handle, selDeveloperExtrasEnabledHandle)); }
public static void SetDeveloperExtrasEnabled(this WebPreferences This, bool enabled) { global::WebKit.Messaging.void_objc_msgSend_bool(This.Handle, selSetDeveloperExtrasEnabled_Handle, enabled); }
static void Main(string[] args) { bool help = false; bool screens = false; string user = null, pass = null; string chatUrl = null, scriptUrl = null; string sessionPath = null; // http://geekswithblogs.net/robz/archive/2009/11/22/command-line-parsing-with-mono.options.aspx OptionSet options = new OptionSet() .Add("?|h|help", "Print this message", option => help = option != null) .Add("u=|user=|username="******"Required: StackExchange username or email", option => user = option) .Add("p=|pass=|password="******"Required: StackExchange password", option => pass = option) .Add("c=|chat-url=", "Required: Chatroom URL", option => chatUrl = option) .Add("b=|bot-script=|script-url=", "Required: The URL of a bot script", option => scriptUrl = option) .Add("s|screens|screenshot", "Display screenshots at checkpoints", option => screens = option != null) .Add("session-path=", "Path to browser session (profile), where settings are saved", option => sessionPath = option); #if DEBUG string[] lines = File.ReadAllLines("account.txt"); user = lines[0]; pass = lines[1]; chatUrl = "http://chat.stackexchange.com/rooms/118/root-access"; scriptUrl = "https://raw.github.com/allquixotic/SO-ChatBot/master/master.js"; screens = true; sessionPath = "session"; #else try { options.Parse(args); } catch (OptionException) { ShowHelp(options, "Error - usage is:"); } if (help) { ShowHelp(options, "Usage:"); } if (user == null) { ShowHelp(options, "Error: A username is required"); } if (pass == null) { ShowHelp(options, "Error: A password is required"); } if (chatUrl == null) { ShowHelp(options, "Error: A chat URL is required"); } if (scriptUrl == null) { ShowHelp(options, "Error: A bot script is required"); } if (sessionPath == null) { sessionPath = "session"; } #endif try { WebConfig config = new WebConfig(); WebCore.Initialize(config); WebPreferences prefs = new WebPreferences(); prefs.LoadImagesAutomatically = true; prefs.RemoteFonts = false; prefs.WebAudio = false; prefs.Dart = false; prefs.CanScriptsCloseWindows = false; prefs.CanScriptsOpenWindows = false; prefs.WebSecurity = false; prefs.Javascript = true; prefs.LocalStorage = true; prefs.Databases = false; // ? aweSession = WebCore.CreateWebSession(sessionPath, prefs); aweSession.ClearCookies(); aweView = WebCore.CreateWebView(1024, 768, aweSession); aweView.ResponsiveChanged += aweView_ResponsiveChanged; aweView.Crashed += aweView_Crashed; aweView.ConsoleMessage += aweView_ConsoleMessage; eView.WebView = aweView; eView.AutoScreenshot = true; eView.ScreenshotsEnabled = screens; go(user, pass, scriptUrl, chatUrl); } finally { if (aweView != null && aweView.IsResponsive) { aweView.Dispose(); } WebCore.Shutdown(); } }
public static void InitializeAwesomium() { WebConfig config = new WebConfig(); config.HomeURL = new Uri("http://w1.dwar.ru"); WebCore.Initialize(config); WebPreferences preferences = new WebPreferences(); WebSession session = WebCore.CreateWebSession(preferences); }
static void Main(string[] args) { bool help = false; bool screens = false; string user = null, pass = null; string chatUrl = null, scriptUrl = null; string sessionPath = null; // http://geekswithblogs.net/robz/archive/2009/11/22/command-line-parsing-with-mono.options.aspx OptionSet options = new OptionSet() .Add("?|h|help", "Print this message", option => help = option != null) .Add("u=|user=|username="******"Required: StackExchange username or email", option => user = option) .Add("p=|pass=|password="******"Required: StackExchange password", option => pass = option) .Add("c=|chat-url=", "Required: Chatroom URL", option => chatUrl = option) .Add("b=|bot-script=|script-url=", "Required: The URL of a bot script", option => scriptUrl = option) .Add("s|screens|screenshot", "Display screenshots at checkpoints", option => screens = option != null) .Add("session-path=", "Path to browser session (profile), where settings are saved", option => sessionPath = option); #if DEBUG string[] lines = File.ReadAllLines("account.txt"); user = lines[0]; pass = lines[1]; chatUrl = "http://chat.stackexchange.com/rooms/118/root-access"; scriptUrl = "https://raw.github.com/allquixotic/SO-ChatBot/master/master.js"; screens = true; sessionPath = "session"; #else try { options.Parse(args); } catch (OptionException) { ShowHelp(options, "Error - usage is:"); } if (help) { ShowHelp(options, "Usage:"); } if (user == null) { ShowHelp(options, "Error: A username is required"); } if (pass == null) { ShowHelp(options, "Error: A password is required"); } if (chatUrl == null) { ShowHelp(options, "Error: A chat URL is required"); } if (scriptUrl == null) { ShowHelp(options, "Error: A bot script is required"); } if (sessionPath == null) { sessionPath = "session"; } #endif try { WebConfig config = new WebConfig(); WebCore.Initialize(config); WebPreferences prefs = new WebPreferences(); prefs.LoadImagesAutomatically = true; prefs.RemoteFonts = false; prefs.WebAudio = false; prefs.Dart = false; prefs.CanScriptsCloseWindows = false; prefs.CanScriptsOpenWindows = false; prefs.WebSecurity = false; prefs.Javascript = true; prefs.LocalStorage = true; prefs.Databases = false; // ? aweSession = WebCore.CreateWebSession(sessionPath, prefs); aweSession.ClearCookies(); aweView = WebCore.CreateWebView(1024, 768, aweSession); aweView.ResponsiveChanged += aweView_ResponsiveChanged; aweView.Crashed += aweView_Crashed; aweView.ConsoleMessage += aweView_ConsoleMessage; eView.WebView = aweView; eView.AutoScreenshot = true; eView.ScreenshotsEnabled = screens; go(user, pass, scriptUrl, chatUrl); } finally { if (aweView != null && aweView.IsResponsive) aweView.Dispose(); WebCore.Shutdown(); } }
static void Main(string[] args) { //AutomationSample main = new AutomationSample(); //main.update(); WebConfig config = WebConfig.Default; WebCore.Initialize(config); Uri url = new Uri("http://www.google.com"); WebPreferences prefs = WebPreferences.Default; //prefs.ProxyConfig = "198.1.99.26:3128"; //prefs.CustomCSS = "body { overflow:hidden; }"; //prefs.WebSecurity = false; //prefs.DefaultEncoding = "UTF-8"; using (WebSession session = WebCore.CreateWebSession(prefs)) { // WebView implements IDisposable. Here we demonstrate // wrapping it in a using statement. using (WebView webView = WebCore.CreateWebView(1366, 768, session, WebViewType.Offscreen)) { bool finishedLoading = false; bool finishedResizing = false; Console.WriteLine(String.Format("Loading: {0} ...", url)); // Load a URL. webView.Source = url; // This event is fired when a frame in the // page finished loading. webView.LoadingFrameComplete += (s, e) => { Console.WriteLine(String.Format("Frame Loaded: {0}", e.FrameId)); // The main frame usually finishes loading last for a given page load. if (e.IsMainFrame) { finishedLoading = true; } }; while (!finishedLoading) { Thread.Sleep(100); // A Console application does not have a synchronization // context, thus auto-update won't be enabled on WebCore. // We need to manually call Update here. WebCore.Update(); } // Print some more information. Console.WriteLine(String.Format("Page Title: {0}", webView.Title)); Console.WriteLine(String.Format("Loaded URL: {0}", webView.Source)); //webView.Render().SaveToPNG("result.png", true); //System.Diagnostics.Process.Start("result.png"); BitmapSurface surface = (BitmapSurface)webView.Surface; surface.SaveToPNG("result.png", true); System.Diagnostics.Process.Start("result.png"); } // Destroy and dispose the view. } // Release and dispose the session. // Shut down Awesomium before exiting. WebCore.Shutdown(); Console.WriteLine("Press any key to exit..."); Console.Read(); }
/// <summary> /// Меняйте настройки WebView здесь. /// if you send null value, the proxy or cache will be established by default. /// Если выберете оконный режим - автоматически при создании браузера открывается новое окно с ним. /// </summary> IWebViewAndAnother CreateWebViewAndAnother(bool isWindowed, string proxyConfigs, string cachePath) { WebViewType viewType; if (isWindowed) { viewType = WebViewType.Window; } else { viewType = WebViewType.Offscreen; } /* * Вот что важного я понял: * - нельзя изменить сессию; * - нельзя изменить IntPtr контрола, где происходит рендеринг. Upd: в wpf вместо него вообще используется WebViewHost; * - нельзя изменить тип отображения ViewType; * - можно отключить рендеринг; * - можно изменить размер; * - можно задать при создании, но нельзя поменять путь к кешу и прокси. */ WebViewAndAnother res = new WebViewAndAnother(); WebView wv = null; InvokeToWebcoreThread(() => { WebPreferences webPreferences = new WebPreferences(); //Настройки с отключенной безопасностью, используйте для тестов. //webPreferences.WebSecurity = false; //webPreferences.CanScriptsAccessClipboard = true; //webPreferences.Databases = true; //webPreferences.FileAccessFromFileURL = true; //webPreferences.JavascriptViewExecute = true; //webPreferences.UniversalAccessFromFileURL = true; //webPreferences.WebGL = true; if (proxyConfigs != null) { webPreferences.ProxyConfig = proxyConfigs; } WebSession ws; if (cachePath == null) { ws = WebCore.CreateWebSession(webPreferences); } else { ws = WebCore.CreateWebSession(cachePath, webPreferences); } wv = WebCore.CreateWebView(1000, 1000, ws, viewType); //Уже не используется. //AddConsoleListener(wv); res.WebSession = ws; if (viewType == WebViewType.Window) { if (EveryTabInOwnWindow || WindowedBrowsersPresenter == null || WindowedBrowsersPresenter.IsClosed) { WindowedBrowsersPresenter = new Window_CustomBrowsersPresenter(); } Window_CustomBrowsersPresenter wbPresenter = WindowedBrowsersPresenter; WebViewHost wwh = new WebViewHost(); wwh.View = wv; var tuple = wbPresenter.AddNewWebViewHost(wwh); TabItem currentTabItem = tuple.Item1; res.WebViewHost = wwh; res.WindowedBrowsersPresenter = wbPresenter; res.BrowsersTabItem = currentTabItem; res.WriteToLog = tuple.Item2.WriteLineToLogs; } else { //if offscreen } }); res.WebView = wv; res.Invoker = InvokeToWebcoreThread; //res.Invoker = (act) => { // InvokeToWebcoreThread(act, wv); //}; return(res); }
private void InitWebView(int width = 1680, int height = 2100) { if (_webView != null) return; timeDomReady = DateTime.MinValue; timeStop = DateTime.MinValue; timeStart = DateTime.MinValue; WebPreferences pref = new WebPreferences(); pref.CustomCSS = "::-webkit-scrollbar { visibility: hidden; }"; pref.AppCache = false; WebSession sess = WebCore.CreateWebSession(pref); _webView = WebCore.CreateWebView(width, height, sess); _webView.DocumentReady += OnDomReady; }