WebBrowser and javascript window.close()

后端 未结 5 1915
挽巷
挽巷 2020-12-19 02:31

If I host a WebBrowser in my application, and a javascript code in the web page shown on my WebBrowser calls window.close() and I click \"Yes\" on

5条回答
  •  -上瘾入骨i
    2020-12-19 03:03

    The best solution in WPF i have found is to use DispatcherTimer:

        private readonly DispatcherTimer _dispatcherTimer;
    
        public MyClass()
        {
            InitializeComponent();
    
            WBrowser.Navigate(loginUri);
    
            _dispatcherTimer = new DispatcherTimer();
            _dispatcherTimer.Tick += dispatcherTimer_Tick;
            _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 200);
            _dispatcherTimer.Start();
        }
    
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (WBrowser.Source == null)
            {
                _dispatcherTimer.Stop();
                Close();
            }
        }
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
    
            if (_dispatcherTimer.IsEnabled)
            {
                _dispatcherTimer.Stop();
            }
        }
    
        private void WBrowser_OnNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if(!_dispatcherTimer.IsEnabled)
            {
                _dispatcherTimer.Start();
            }
        }
    

提交回复
热议问题