Объект помощника браузера для выполнения JavaScript в Internet Explorer 11

Я искал в Интернете примеры объекта Browser Helper, который выполняет JS, и зашел так далеко, но JS, похоже, не выполняется. Код приведен ниже, и я также запустил regasm.exe codebase/ в dll, но, похоже, ничего не происходит, когда я загружаю расширение в браузере - какие-либо предложения?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using SHDocVw;
using mshtml;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace My_BHO
{
    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
    public interface IObjectWithSite
    {
        [PreserveSig]
        int SetSite([MarshalAs(UnmanagedType.IUnknown)] object site);

        [PreserveSig]
        int GetSite(ref Guid guid, out IntPtr ppvSite);
    }
    [
        ComVisible(true),
        Guid("2159CB25-EF9A-54C1-B43C-E30D1A4A8277"),
        ClassInterface(ClassInterfaceType.None)
    ]

    public class BHO : IObjectWithSite
    {
        private WebBrowser webBrowser;
        public const string BHO_REGISTRY_KEY_NAME = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";

        public int SetSite(object site)
        {
            if (site != null)
            {
                webBrowser = (WebBrowser)site;
                webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
            }
            else
            {
                webBrowser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
                webBrowser = null;
            }
            return 0;
        }

        public int GetSite(ref Guid guid, out IntPtr ppvSite)
        {
            IntPtr punk = Marshal.GetIUnknownForObject(webBrowser);
            int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
            Marshal.Release(punk);
            return hr;
        }

        public void OnDocumentComplete(object pDisp, ref object URL)
        {
            HTMLDocument document = (HTMLDocument)webBrowser.Document;
            IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)document.all.tags("head")).item(null, 0);
            IHTMLScriptElement adaptiveScript = (IHTMLScriptElement)document.createElement("script");
            adaptiveScript.type = @"text/javascript";
            adaptiveScript.text = "alert('hi');";
            ((HTMLHeadElement)head).appendChild((IHTMLDOMNode)adaptiveScript);
        }

        [ComRegisterFunction]
        public static void RegisterBHO(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);
            if (registryKey == null) registryKey = Registry.LocalMachine.CreateSubKey(BHO_REGISTRY_KEY_NAME);

            string guid = type.GUID.ToString("B");
            RegistryKey ourKey = registryKey.OpenSubKey(guid, true);
            if (ourKey == null) ourKey = registryKey.CreateSubKey(guid);
            ourKey.SetValue("NoExplorer", 1, RegistryValueKind.DWord);

            registryKey.Close();
            ourKey.Close();
        }

        [ComUnregisterFunction]
        public static void UnregisterBHO(Type type)
        {
            RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);
            string guid = type.GUID.ToString("B");
            if (registryKey != null) registryKey.DeleteSubKey(guid, false);
        }
    }

}

В основном я пытался следовать этому руководству, но был бы признателен за любые другие более свежие примеры! https://www.codeproject.com/Articles/149258/Inject-HTML-and-JavaScript-into-an-existing-page-w

Может быть, что-то с GUID не так?

Заранее спасибо!


person McD    schedule 21.01.2020    source источник
comment
Я следовал руководству, и надстройка кажется несовместимой с IE 11: i.stack.imgur.com /dMxXh.png. Вы можете проверить информацию о вашем дополнении в IE. Вы также можете попробовать отключить расширенный защищенный режим, чтобы увидеть, может ли надстройка работать. Кроме того, я нашел более свежий пример, который вы мог бы обратиться.   -  person Yu Zhou    schedule 21.01.2020
comment
Поддержка элементов управления ActiveX была строго ограничен в IE11, чтобы отвлечь людей от элементов управления ActiveX и BHO. Вы должны добавить на страницу метатег x-ua-compatible, который работает только в IE для рабочего стола. (Они вообще не работают в Edge.) В наши дни ожидается, что вы будете разрабатывать надстройки для браузера как Расширения Chrome.   -  person Lance Leonard    schedule 23.01.2020
comment
Спасибо вам обоим! @YuZhou, этот более новый пример (и возня с загадочными настройками IE11) сработал!   -  person McD    schedule 29.01.2020
comment
Кажется, вы решили проблему. Вы также можете поместить свое решение в качестве ответа и пометить его как принятый ответ через 48 часов, когда оно будет доступно для отметки. Это может помочь другим членам сообщества в будущем в подобных вопросах. Спасибо за понимание.   -  person Yu Zhou    schedule 31.01.2020