CEF 37.0.0 Disable Javascript

Having problems with building or using CEF's C/C++ APIs? This forum is here to help. Please do not post bug reports or feature requests here.

CEF 37.0.0 Disable Javascript

Postby abiramir » Thu Jan 28, 2016 1:10 pm

I want to disable the javacripts in CEF browser. I referred this post http://magpcss.org/ceforum/viewtopic.php?f=6&t=13462&p=27803&hilit=disable+javascript#p27803, and tried to set the javascript property of CefSettings. But there is no property exist in the version 37.0.0.

Could anyone advise on how to disable the particular javascript file in a website rendered in CEF browser.

[Note: The javascript in the webpage actually taking us to another webpage and we really don't want that to happen]

Any help would be highly appreciated!!

Thanks!!
abiramir
Newbie
 
Posts: 4
Joined: Thu Jan 28, 2016 10:28 am

Re: CEF 37.0.0 Disable Javascript

Postby magreenblatt » Thu Jan 28, 2016 1:26 pm

The value exists in CefBrowserSettings, not CefSettings.
magreenblatt
Site Admin
 
Posts: 12408
Joined: Fri May 29, 2009 6:57 pm

Re: CEF 37.0.0 Disable Javascript

Postby abiramir » Thu Jan 28, 2016 4:08 pm

Hi magreenblatt,

Thanks for your reply. Is CefBrowserSettings available in the version [37.0.0] I am using. Also the Cef.Initialize method accepting only the CefSettings object. [There are no overloaded method to accept both CefSettings and CefBrowserSettings]

Could you please advise

Thanks!!
abiramir
Newbie
 
Posts: 4
Joined: Thu Jan 28, 2016 10:28 am

Re: CEF 37.0.0 Disable Javascript

Postby magreenblatt » Thu Jan 28, 2016 5:16 pm

It exists in the C++ API and is passed to CefBrowserHost::CreateBrowser. It sounds like you're using some type of wrapper project. You should check the documentation for that wrapper.
magreenblatt
Site Admin
 
Posts: 12408
Joined: Fri May 29, 2009 6:57 pm

Re: CEF 37.0.0 Disable Javascript

Postby abiramir » Fri Jan 29, 2016 2:55 pm

Hi magreenblatt,

Thanks again for your prompt response.

Below is the code I am using in my console application to render a web page offscreen and logging in to that. It seems that the web page itself not rendered and in the OnBrowserConsoleMessage event, I am getting an error message
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened
and not the HTML content of the page. Could you please advise.. Thanks!!

Code: Select all
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using CefSharp.OffScreen;
using CefSharp;
using System.Text;
using System.Linq;
using System.Threading;
using System.ComponentModel;


namespace TestCEF
{
    public class Program
    {       
        const string WebURL = "URL";

        private static ChromiumWebBrowser browser;

        public static void Main(string[] args)
        {
            try
            {
                WriteToConsole("Initializing...", true);
                Init();
                StartProcessQueue();
                System.Console.ReadKey();
                Cef.Shutdown();
            }
            catch (Exception ex)
            {
                WriteToConsole(string.Format("ERROR: {0}", ex.Message), true, false);
                WriteToConsole(string.Format("APPLICATION STOPPED. RESTART REQUIRED!!!", ""), true, false);
            }
        }
       
        private static void Init()
        {
            var settings = new CefSettings();
            settings.RemoteDebuggingPort = 8088;
            settings.LogSeverity = LogSeverity.Default;

            settings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
                SchemeHandlerFactory = new CefSharpSchemeHandlerFactory()
            });
           
            if (!Cef.Initialize(settings))
            {
                if (Environment.GetCommandLineArgs().Contains("--type=renderer"))
                {
                    Environment.Exit(0);
                }
                else
                {
                    return;
                }
            }
        }               

        private static bool StartProcessQueue()
        {
            if (browser != null)
            {
                browser.Dispose();
                browser = null;
            }

            try
            {               
                browser = new ChromiumWebBrowser();
            }
            catch (Exception ex)
            {
                if (ex.Message.ToUpper().Contains("FAILED TO CREATE OFFSCREEN BROWSER. CALL CEF.INITIALIZE() FIRST."))
                {
                    Init();
                    browser = new ChromiumWebBrowser();
                }
                else
                    throw ex;
            }
           
            browser.FrameLoadEnd += BrowserFrameLoadEnd;
            browser.ConsoleMessage += OnBrowserConsoleMessage;           
            browser.Load(WebURL);

            return true;
        }       

        private static void BrowserFrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            try
            {
                if (e.IsMainFrame)
                {
                    browser.ExecuteScriptAsync("console.log(document.documentElement.outerHTML);");
                }
            }
            catch (Exception ex)
            {
                WriteToConsole(string.Format("ERROR: {0}", ex.Message), true, false);               
                StartProcessQueue();
            }
        }

        private static void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs e)
        {
            try
            {
                string JavascriptTemplate = "";

                var HTMLContent = e.Message.ToUpper();
                if (HTMLContent.Contains("LOGIN"))
                {
                    WriteToConsole("Loading login template", true, false);

                    JavascriptTemplate = GetLoginTemplate();
                }
                else if (HTMLContent.Contains("SEARCH"))
                {
                    WriteToConsole("Loading search template", true, false);

                    JavascriptTemplate = GetIndividualSearchTemplate();

                    if (string.IsNullOrEmpty(JavascriptTemplate))
                        return;
                    // HERE WE ARE DOING OTHER STEPS
                }             
                else
                {
                    WriteToConsole(string.Format("Handler cant not be found for the Webpage URL {0} or its Content!!!", browser.Address), true);
                    return;
                }

                if (!string.IsNullOrEmpty(JavascriptTemplate))
                {
                    WriteToConsole("Running template...", true);
                    browser.ExecuteScriptAsync(JavascriptTemplate);
                }
                else
                    throw new Exception("Empty template!!!");
            }
            catch (Exception ex)
            {
                WriteToConsole(string.Format("ERROR: {0}", ex.Message), true, false);               
                StartProcessQueue();
            }
        }

        #region JavaScript Templates
       
        public static string GetLoginTemplate()
        {
            return "if (document.getElementById(\"login:loginName\") != null) { document.getElementById(\"login:loginName\").value = \"LOGINANME\"; } " +
                   "document.getElementById(\"login:password\").value = \"PASSWORD\";" +               
                   "var LoginFormButtons = document.getElementsByTagName(\"button\");" +
                   "for (var i = 0, len = LoginFormButtons.length; i < len; ++i) { if (LoginFormButtons[i].innerHTML.indexOf(\"Login</span>\") != -1) { LoginFormButtons[i].click(); } };";
        }

        public static string GetIndividualSearchTemplate()
        {           
            return string.Format("changeForm('OPTION');" +
                   "document.range.ID.value='12434';" +
                   "document.range.NAME.value='NAME';" +
                   "document.getElementById('submit').click();");
        }

        #endregion
       
        private static void WriteToConsole(string Message, bool NewLine = false, bool WriteDateTimeStamp = true)
        {
            if (NewLine)
                System.Console.WriteLine();
            System.Console.WriteLine(string.Format("{0}{1}", (WriteDateTimeStamp) ? DateTime.Now.ToString() + " :- " : "", Message));
        }
    }

    internal class CefSharpSchemeHandlerFactory : ISchemeHandlerFactory
    {
        public const string SchemeName = "custom";

        public ISchemeHandler Create()
        {
            return new CefSharpSchemeHandler();
        }
    }

    internal class CefSharpSchemeHandler : ISchemeHandler
    {
        private readonly IDictionary<string, string> resources;

        public CefSharpSchemeHandler()
        {
            resources = new Dictionary<string, string>
            {
                { "/home", Resources.home_html },

                { "/assets/css/shCore.css", Resources.assets_css_shCore_css },
                { "/assets/css/shCoreDefault.css", Resources.assets_css_shCoreDefault_css },
                { "/assets/css/docs.css", Resources.assets_css_docs_css },
                { "/assets/js/application.js", Resources.assets_js_application_js },
                { "/assets/js/jquery.js", Resources.assets_js_jquery_js },
                { "/assets/js/shBrushCSharp.js", Resources.assets_js_shBrushCSharp_js },
                { "/assets/js/shCore.js", Resources.assets_js_shCore_js },

                { "/bootstrap/bootstrap-theme.min.css", Resources.bootstrap_theme_min_css },
                { "/bootstrap/bootstrap.min.css", Resources.bootstrap_min_css },
                { "/bootstrap/bootstrap.min.js", Resources.bootstrap_min_js },

                { "/BindingTest.html", Resources.BindingTest },
                { "/PopupTest.html", Resources.PopupTest },
                { "/SchemeTest.html", Resources.SchemeTest },
                { "/TooltipTest.html", Resources.TooltipTest },
            };
        }

        public bool ProcessRequestAsync(IRequest request, ISchemeHandlerResponse response, OnRequestCompletedHandler requestCompletedCallback)
        {
            // The 'host' portion is entirely ignored by this scheme handler.
            var uri = new Uri(request.Url);
            var fileName = uri.AbsolutePath;

            string resource;
            if (resources.TryGetValue(fileName, out resource) &&
                !String.IsNullOrEmpty(resource))
            {
                var bytes = Encoding.UTF8.GetBytes(resource);
                response.ResponseStream = new System.IO.MemoryStream(bytes);
                response.MimeType = GetMimeType(fileName);
                requestCompletedCallback();

                return true;
            }

            return false;
        }

        private string GetMimeType(string fileName)
        {
            if (fileName.EndsWith(".css")) return "text/css";
            if (fileName.EndsWith(".js")) return "text/javascript";

            return "text/html";
        }
    }   
}

abiramir
Newbie
 
Posts: 4
Joined: Thu Jan 28, 2016 10:28 am

Re: CEF 37.0.0 Disable Javascript

Postby magreenblatt » Fri Jan 29, 2016 2:58 pm

I already responded to your question in viewtopic.php?f=6&t=13836. Please don't post the same question to multiple threads.
magreenblatt
Site Admin
 
Posts: 12408
Joined: Fri May 29, 2009 6:57 pm


Return to Support Forum

Who is online

Users browsing this forum: Google [Bot] and 59 guests