Отладка CustomScheme в CefSharp - PullRequest
       141

Отладка CustomScheme в CefSharp

0 голосов
/ 19 сентября 2019

Я выполняю миграцию загрузчика файлов пользовательской схемы, который я написал в CefSharp (Chromium Embedded Web Host для Windows Forms).Я не смог заставить его работать на другом сервере.Я экспериментирую с новыми конфигурациями, но я не уверен, где во время выполнения мне нужно проверить, чтобы убедиться, что папки, которые я надеюсь найти в моих html-файлах, являются реальными целями.

CefPrimeFiles - это rootFolder.ScanditPage - это папка вниз, представляющая местоположение html, поэтому целевым URL является http://localhost/ScanditPage/ScanditTest.html.

. RootFolder для FolderSchemeHandlerFactory - C: \ Users \ romero.ryan \ Documents \ Visual Studio 2015 \ Projects \WinHostScandit1 \ WebHostOnDisk \ CefPrimeFiles.

У объекта браузера есть .Address дает мне целевой URL.Я предполагаю, что Cef. * Будет содержать информацию о зарегистрированных схемах, но пока я не нашел ссылку при отладке.

Вот рабочий пример (кроме ошибки формы при загрузке целевого файла HTML):

StaticCustomBrowser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CefSharp;
using CefSharp.WinForms;
using System.IO;
using CefSharp.SchemeHandler;
using System.Windows.Forms;
using System.Diagnostics;

namespace ScannerForm
{
    public static class StaticCustomBrowser
    {
        public static ChromiumWebBrowser browser;
        public static Form popup;
        public static Stopwatch sw1 {
            get; set; }

        public static CefSettings CWSettings { get; set; }
        public static BrowserSettings CWBrowserSettings { get; set; }
        public static JSObj1 Messenger { get; set; }
        public static string baseURL { get; set; }

        public static string rootFolder { get; set; }

        public static string defaultPage { get; set; }

        public static string DomainName { get; set; }

        public static void DefaultCefSettings()
        {


            CWSettings.CefCommandLineArgs.Add("enable-media-stream", "enable-media-stream");
            CWSettings.CefCommandLineArgs.Add("allow-file-access-from-files", "allow-file-access-from-files");
            CWSettings.CefCommandLineArgs.Add("disable-web-security", "disable-web-security");
            CWSettings.PersistSessionCookies = true;


            CWSettings.JavascriptFlags = "--expose-wasm";

        }


        public static void DefaultBrowserSettings()
        {
            CWBrowserSettings.FileAccessFromFileUrls = CefState.Enabled;
            CWBrowserSettings.LocalStorage = CefState.Enabled;
            CWBrowserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
            CWBrowserSettings.WebSecurity = CefState.Disabled;
            //browser.BrowserSettings = CWBrowserSettings;
        }


        public static BrowserSettings browserSettings()
        {
            BrowserSettings bs = new BrowserSettings();

            bs.FileAccessFromFileUrls = CefState.Enabled;
            bs.LocalStorage = CefState.Enabled;
            bs.UniversalAccessFromFileUrls = CefState.Enabled;
            bs.WebSecurity = CefState.Disabled;


            return bs;
        }



        public static void CustomFolderURLLoader(string inURL)
        {
            if (!Directory.Exists(CWSettings.CachePath))
            {
                throw new NotImplementedException();

            }

            DefaultCefSettings();
            // DefaultBrowserSettings();

            browser.BrowserSettings = browserSettings();

            //AddFakeURLScheme();
            HttpResourceHandler();

            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            init();
            browser.RegisterAsyncJsObject("boundAsync", Messenger, null);
            browser.Dock = DockStyle.Fill;
            browser.Name = "browser";
            browser.LoadingStateChanged += DefaultFrameLoad;
            browser.Load(inURL);


            var text = "";

        }

        public static void init()
        {
            if (!Cef.IsInitialized)
            {
                Cef.Initialize(CWSettings);
            }


        }

        public static void HttpResourceHandler()
        {

            try
            {
                string SchemeName = "http";
                FolderSchemeHandlerFactory newFac = new FolderSchemeHandlerFactory(rootFolder, null, DomainName, defaultPage);

                CefCustomScheme FakeURLScheme = new CefCustomScheme();
                FakeURLScheme.SchemeName = SchemeName;
                FakeURLScheme.SchemeHandlerFactory = newFac;
                FakeURLScheme.IsCorsEnabled = true;
                FakeURLScheme.IsFetchEnabled = true;
                FakeURLScheme.IsLocal = true;

                FakeURLScheme.DomainName = DomainName;
                CWSettings.RegisterScheme(FakeURLScheme);
            }
            catch (Exception ex) { throw; }

        }

        public static void ShowDevtools() { browser.ShowDevTools(); }

        public static void DefaultFrameLoad(object sender, LoadingStateChangedEventArgs e)
        {

        //    var cmanager = Cef.GetGlobalCookieManager();

            if (!e.IsLoading)
            {
                CefSharpSettings.LegacyJavascriptBindingEnabled = true;
                //setScanditCookie();
                ShowDevtools();

            }

        }

        //StaticScanditLibrary.StaticScandit.ShowDialog(this, "textBox1");


        public static string ShowDialog2(Form frm1, string textBoxName,string url,string CachePath)
        {
            popup = new Form()
            {

                Width = 1000,
                Height = 500,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                //Text = caption,
                StartPosition = FormStartPosition.CenterScreen

            };

            /*
            this.textBoxOut1.Location = new System.Drawing.Point(129, 55);
            this.textBoxOut1.Name = "textBoxOut1";
            this.textBoxOut1.Size = new System.Drawing.Size(384, 20);
            this.textBoxOut1.TabIndex = 2;
            */


            CWSettings = new CefSettings();
            CWBrowserSettings = new BrowserSettings();
            browser = new ChromiumWebBrowser();
            baseURL = url;
          //  this.Messenger = mess;
           // this.rootFolder = rootFolder;
            //this.DomainName = DomainName;
            CWSettings.CachePath = CachePath;
            //this.defaultPage = defaultPage;
            //CustomFolderURLLoader(url);



            popup.Visible = true;
            return "";
        }



        public static void ShowDialog(string url, string DomainNameIn, string rootFolderIn, string defaultPageIn, string CachePath, TextBox inTB)
        {

            popup = new Form()
            {

                Width = 1000,
                Height = 500,
                FormBorderStyle = FormBorderStyle.FixedDialog,
                //Text = caption,
                StartPosition = FormStartPosition.CenterScreen

            };



            TextBox myTB = new TextBox();
            //myTB.Width = 50;
            //myTB.Height = 50;
            myTB.Name = "myTB";
            myTB.Size = new System.Drawing.Size(184, 20);
            //myTB.Location = new System.Drawing.Point(129, 55);
            myTB.Location = new System.Drawing.Point(10, 10);
            popup.Controls.Add(myTB);




            CWSettings = new CefSettings();
            CWBrowserSettings = new BrowserSettings();
            browser = new ChromiumWebBrowser();
            baseURL = url;
          //  Messenger = mess;
            rootFolder = rootFolderIn;
            DomainName = DomainNameIn;
            CWSettings.CachePath = CachePath;
            defaultPage = defaultPageIn;


             Messenger = new JSObj1(inTB, popup);


            CustomFolderURLLoader(url);
            popup.Controls.Add(browser);
            popup.Visible = true;
            //return "";

        }

    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinHostScandit1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using ScannerForm;

namespace WinHostScandit1
{
    public partial class Form1 : Form
    {

        public static Stopwatch sw = new Stopwatch();
        public static ScannerForm.CustomBrowser mycb ;
        Form ScanditForm;

        public Form1()
        {
            InitializeComponent();


            JSObj1 Mess = new JSObj1(this.textBoxOut1, this);
            //mycb.Messenger = new JSObj1(this.textBox1, this);
            mycb = new ScannerForm.CustomBrowser(Mess);

            ScanditForm = new ScannerForm.ScanditPopupForm(this.textBoxOut1);

            this.textBoxOut1.TextChanged += TextChanged;
            ScanditForm.Visible = false;

        }

        private void button1_Click(object sender, EventArgs e)
        {


            //public static void ShowDialog(string url, string DomainNameIn, string rootFolderIn, string defaultPageIn, string CachePath, TextBox inTB)

            string inUrl="http://localhost/ScanditPage/ScanditTest.html";
            string DomIn = "localhost";
            string rootFolder = @"C:\Users\romero.ryan\Documents\Visual Studio 2015\Projects\WinHostScandit1\WebHostOnDisk\CefPrimeFiles";
            string defaultPageIn = "ScanditTest.html";
            string CachePath = @"C:\Users\romero.ryan\Documents\Visual Studio 2015\Projects\WinHostScandit1\WebHostOnDisk\CEF";


            ScannerForm.StaticCustomBrowser.ShowDialog(inUrl, DomIn, rootFolder, defaultPageIn, CachePath, this.textBoxOut1);




            /*
            sw.Start();
              mycb.CustomFolderURLLoader("http://localhost/ScanditPage/ScanditTest.html");
             mycb.browser.Visible = true;

            // ScanditForm.Visible = true;

            ScanditForm.Visible = true;*/


        }


        private void TextChanged (object sender, EventArgs e)
        {

            sw.Stop();

            Console.WriteLine("Elapsed={0}", sw.Elapsed);
            var milliseconds = sw.Elapsed.TotalMilliseconds;
            sw.Restart();

            string Entry = this.textBoxOut1.Text;
            if (!String.IsNullOrEmpty(Entry)) { this.textBoxOut1.Text = ""; }


        }


    }
}

JSObj1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ScannerForm
{
    public class JSObj1
    {

        public string CameraList { get; set; }


        // Dictates where to store read of barcode. 
        public TextBox TB { get; set; }

        public EventHandler EH { get; set; }

        //Defines which Caller to make visible/invisible. 
        public Form WebHostForm { get; set; }

        public JSObj1(TextBox inTB, Form inForm)
        {
            TB = inTB;
            WebHostForm = inForm;
        }

        public void setCameraList(string input)
        {
            CameraList = input;

        }




        public void showMessage(string msg)
        {
            //  MessageBox.Show(msg);
            Form target = (Form)TB.Parent;

            TB.Invoke((Action)(() => { TB.Text = msg; }));
            //TB.Invoke((Action)(() => { TB.FindForm().Visible = true; WebHostForm.Visible = false; }));
            TB.Invoke((Action)(() => { TB.FindForm().Visible = true; WebHostForm.Visible = true; }));

        }

    }
}

ScanditTest.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Scandit Web SDK WXYS</title>

    <!-- Add the library, as explained on http://docs.scandit.com/stable/web/index.html -->


    <script src="/scandit-sdk/build/browser/index.min.js"></script>


    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: black;
            color: white;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: center;
            font-size: 3vh;
            font-family: 'Open Sans', sans-serif;
            width: 100vw;
            height: 100vh;
        }

        #scandit-barcode-picker {
            width: 100%;
            height: 100%;
            max-height: 70vh;
        }

        #scandit-barcode-result {
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            width: 100%;
        }

        button,
        button:active,
        button[disabled]:hover {
            --webkit-appearance: none;
            border: none;
            border-radius: none;
            outline: none;
            font-size: 0.7em;
            padding: 0.4em 0.6em;
            margin: 20px;
            text-transform: uppercase;
            font-family: 'Open Sans', sans-serif;
            background: #2ec0cc;
            color: white;
        }

            button:hover {
                background: #30d0d8;
            }

            button[disabled] {
                opacity: 0.4;
            }

        #continue-scanning-button {
            margin-bottom: 10vh;
        }
    </style>

</head>

<body>

    <script type="text/javascript">
        function continueScanning() {
            if (picker) {
                continueButton.disabled = true;
                // Resume scanning
                picker.resumeScanning();
            }
        }





    </script>




    <!-- Containers for the picker and the results -->
    <select name="camlist" id="camlist"></select>
    <div id="scandit-barcode-picker"></div>
    <div>another test phrase</div>
    <div id="scandit-barcode-result">No codes scanned yet blah</div>
    <button onclick="TestA();">Push Me</button>
    <!-- Button to continue scanning after a barcode was scanned -->
    <button id="continue-scanning-button" onclick="continueScanning()">Continue Scanning</button>


    <script>
        // Helper function called when the "Continue Scanning" button is clicked


        function doReduceTrue(string, barcode) {
            //var ans2 = ScanditSDK.Barcode.Symbology.toHumanizedName(barcode.symbology) + ": " + barcode.data;
            var ans2 = barcode.data;
            return ans2;
        }

        function TestA() { alert("Testing Stuff Agains!"); }

        function consoleError(x) { console.log(x); }

        function PopulateCameraList(clist) {
            console.log(clist);
            //var samp = "<option value=\"3\">tree</option>";
            var samp = "";
            clist.forEach(
                    function (element) { samp = "<option value=\"" + element.deviceId + "\">" + element.label + "</option>"; }

                );

            document.getElementById("camlist").innerHTML = samp;
            boundAsync.CameraList = samp;
            boundAsync.setCameraList(samp);

        }


        function alerError(x) { alert(x); }

        function onScan(scanResult) {
            continueButton.hidden = false;
            continueButton.disabled = false;

           // picker.pauseScanning();

            var scanned = scanResult.barcodes.reduce(

            doReduceTrue,


                ''

                );



            resultContainer.innerHTML = scanned;
            boundAsync.showMessage(scanned);


        }


        function MyBCPicker(barcodePicker) {

            picker = barcodePicker;


            picker.pauseScanning();

            const scanSettings = new ScanditSDK.ScanSettings({
                enabledSymbologies: [ "upca", "upce", "code39" ],
                codeDuplicateFilter: 1000
            });


            picker.applyScanSettings(scanSettings);
            // If a barcode is scanned, show it to the user and pause scanning
            // (scanning is resumed when the user clicks "Continue Scanning")
            picker.onScan(
        onScan

            );


            picker.onScanError(consoleError);


              picker.resumeScanning();
        }


        // Configure the library and activate it with a license key
        const licenseKey = "ATjtVA+vEutFHOV9xjZ7YpQidNFzDLM431cx19c+r5gqe1jIzR2bTU9vTX2qSawX/Gr+L4ZnfTvSTsPqjFOsKEBzuwyUSTk0zWIgTNFjTGFhf87MfG7Skzo+6tNKM2poNDok/CfOdwFuKsTUIEkfp1ZO+hbGBZ60yUgmVcq/suJsQH3QYfw1MmdCQgblo5H7NbwIzXM1yOHUpzs3pB1dosaUzG3fg/Xq5Szt0GCxP86XNWFFYXRZC45GgamChPZGA5n8c2FRlBtLU8W+1xxQOe7Pq17kbNSe2ZkGSdcR7Oi/H4WPGW1rSqQBRenSnsnFsPDMaLbGJ6S37DEPkNoUZJCc4iJ1y18mac7fQT5Vibegt0paIpA+yD+Z28sIHbiQV+hHYEMGr2Es4QmqjFzJ/dt2d9lGKCofbOEQREpG4cuhNFlQMCSjmVheONbx6UeD94P4M5Ktjf/vZc4TsoguL1R1R9Cmp8/aTUX4n4oE5HTmzreE0ARq2V7lffUB1uj0lyV3tjTQPJeUJnN+xlCs0zs8y5bxhyALte6scDV1lE1zTthdgnyMHGD+SSE6KH/Nlr6RTs3UsbyXb/E0m714eAowi7nYC/lyAG65FRxDuoU/vRggrtsDyeXwfqtYGcPaYjRsi6eF+JW3Sk4gO8iEPXEbymL6kUogyEPm20XGfMKLBz9+pwGFO8tezzSf00ESQkNMDNgqAfetqtdKYmHaGu1lLWJj4V/picrBiUuhftfqbxvO5o4f3OAEiBtmwJEDbL/1EeYylrWZ9ZTWqAaMdUuRQytaawrd0CJLoAzZS+C95A==";
        // Configure the engine location, as explained on http://docs.scandit.com/stable/web/index.html
        // const engineLocation = "build"; // the folder containing the engine
        // or, if using a CDN:


        //const engineLocation = "/users/romero.ryan/documents/visual studio 2015/projects/WinHostScandit1/WebHostOnDisk/CefPrimeFiles/scandit-sdk/build";
        const engineLocation = "/scandit-sdk/build";

        ScanditSDK.configure(licenseKey, { engineLocation: engineLocation });
        const scannerContainer = document.getElementById("scandit-barcode-picker");
        const resultContainer = document.getElementById("scandit-barcode-result");
        const continueButton = document.getElementById("continue-scanning-button");
        continueButton.disabled = true;
        continueButton.hidden = true;

        console.log(ScanditSDK);
        let picker;
        ScanditSDK.CameraAccess.getCameras().then(PopulateCameraList);


        // Create & start the picker
        ScanditSDK.BarcodePicker.create(scannerContainer, {
            playSoundOnScan: true,
            vibrateOnScan: true,
        //  scanningPaused:true,

        })
            .then(


        MyBCPicker)
            .catch(alerError);
    </script>



</body>

</html>

Layout on Disk of Relevant HTML

...