chromelyapps / Chromely

Build Cross Platform HTML Desktop Apps on .NET using native GUI, HTML5, JavaScript, CSS, Owin, AspNetCore (MVC, RazorPages, Blazor)
MIT License
2.99k stars 279 forks source link

Howto: Get page source text #352

Closed mattkol closed 2 years ago

mattkol commented 2 years ago

To get page source use Frame GetSource:

https://github.com/chromelyapps/Chromely/blob/1f95b7d1475cd56bd9a50b1d8df7140e42810e22/src/Chromely/CefGlue/Classes.Proxies/CefFrame.cs#L95

CrossPlatDemo.zip

  1. Create a handler to get the source:
 internal class SourceTextHandler 
    {
        protected IChromelyConfiguration _config;

        public SourceTextHandler(IChromelyConfiguration config)
        {
            _config = config;
        }

        public void WriteSourceTextToFile(string filename)
        {
            CefFrame frame = _config?.JavaScriptExecutor?.GetMainFrame() as CefFrame;
            if (frame == null)
            {
                return;
            }

            var visitor = new SourceVisitor((text) =>
                                            {
                                                if (!string.IsNullOrWhiteSpace(text))
                                                {
                                                    System.IO.File.WriteAllText(filename, text);
                                                }
                                            });

            frame.GetSource(visitor);
        }

        private sealed class SourceVisitor : CefStringVisitor
        {
            private readonly Action<string> _callback;

            public SourceVisitor(Action<string> callback)
            {
                _callback = callback;
            }

            protected override void Visit(string value)
            {
                _callback(value);
            }
        }
    }
  1. Create a command action:
        [CommandAction(RouteKey = "/democontroller/getsource")]
        public void Getsource(IDictionary<string, string> queryParameters)
        {
            var textHandler = new SourceTextHandler(_config);
            textHandler.WriteSourceTextToFile("source_text.txt");
        }
  1. Add html button:
<a href="http://command.com/democontroller/getsource" class="btn btn-primary" role="button" style='margin: 5px;'>get source</a>

Ref: https://www.magpcss.org/ceforum/viewtopic.php?f=6&t=929

image