• 0

"Function Expected" IE10 Script Error on Disposing of WebBrowser ST


Question

Point of application,

Render Provided html string and print it using Internet Explorer, quickly in the background.

Problem,

WebBrowser control requires to be run in an STA thread stopping this thread (after Disposing the Web Browser) causes an IE script error.

I have a class which starts a WebBrowser Control in an STA thread,

    class RenderHtml : System.Windows.Forms.ApplicationContext
    {
// stuff
        private WebBrowser browser = null;
// more stuff
        public RenderHtml()
        {
            renderThread = new Thread(Run);
            renderThread.SetApartmentState(System.Threading.ApartmentState.STA);
            renderThread.Start();
        }

        private void Run()
        {
// Error Checking Omitted
                    browser = new WebBrowser();
                    browser.DocumentCompleted += HasRendered;
                    browser.ScriptErrorsSuppressed = true;
            Application.Run(this);

Then, I give pipe it Html to load,

        public void RenderNew(string html, AutoResetEvent resultEvent)
        {
// Error Checking Omitted
                    browser.DocumentText = html;
                    browser.Refresh();
// AutoResetEvent Logic Omitted
        }

Then after it finished rendering, I tell it to print to a specific virtual printer.

That all works.

So now, I need to dispose of it.

This is what I have right now

        protected override void Dispose(bool disposing)
        {
            lock (locko)
            {
                if (renderThread != null)
                {
                    renderThread.Abort();
                    renderThread = null;
                    return;
                }
            }
            browser.DocumentCompleted -= HasRendered;
            System.Runtime.InteropServices.Marshal.Release(browser.Handle);
            browser.Dispose();
            base.Dispose(disposing);
        }

        public void Stop()
        {
            resultEvent.Dispose();

            browser.Stop();
            ExitThread();
            Dispose();
        }

The problem is with both renderThread.Abort() and ExitThread() - I have to commit both out not to get an error.

Both of these fail due to the WebBrowser control.

I don't feel like providing a screenshot, so here is the text,

The error comes from IE itself,

Script Error
An error has occurred in the script on this page.
Line: 289
Char: 1
Error: Function Expected
Code: 0
URL: res://ieframe.dll/preview.js

Do you want to continue running scripts on this page?

So, after calling Dispose methods including the WebBrowsers dispose method.

I try to stop the thread. Which gives me this error.

If I did NOT provide any html to render I think (been a long time) there is no Script Error.

But then, it completely kills the point of the application!

Note I do suppress Script Errors - when I created the WebBrowser.

                    browser.ScriptErrorsSuppressed = true;

Also, does anyone know of a way to provide images to the WebBrowser control without going through saving them to disk?

2 answers to this question

Recommended Posts

  • 0

EDIT: Code is Available if you have no f-ing idea what I am talking about.

Now to dispose a WebBrowser,

I can do it from the STA Thread Which runs the Web Browser using Application.run(this).

So I can dispose the WebBrowser when it triggers an even such as a DocumentCompleted event.

Additionally, I can dispose of the Web Browser by using .Invoke(...) method.

Sadly WebBrowser cannot be disposed of from another thread by simply calling the Dispose() method.

I can also set the reference to the STA thread to null as well well as the reference to the WebBrowser

and set the thread to be a background thread.

The issue is, the thread does not terminate.

And to release all memory I have to terminate the damn thread.

Whether before or after dispose, whether from a separate thread or the STA Thread itself (during the DocumentCompleted event)

I get this error.

I guess I am asking is, how am I supposed to properly stop a ApplicationContext with a Web Browser Control properly and dispose of it WITHOUT any errors?

1. Why doesn't the renderThread exit itself (Abort is bad from what I understand)?

2. From where do I Abort the renderThread (STA Thread)? The calling thread (which uses the code)? renderThread itself?

3. Do I abort the thread before or after disposing of the WebBrowser?

4. Is the most proper way to dispose of a WebBrowser from another (calling) thread is to use browser.Invoke(...)?

5. Now there is Exit() ExitThread() renderThread.Abort() ExitThreadCore() - they all give me the same error... where am I supposed to call them to avoid bull?

Also this error may help,

A first chance exception of type 'System.Runtime.InteropServices.InvalidComObjectException' occurred in System.Windows.Forms.dll

Edited by _Alexander
  • 0

Workaround Solution

Even after calling browser.Dispose(),

waiting for the browser.Disposed event handler to finish,

and checking browser.IsDisposed before calling renderThread.Abort()

I still got the dreaded Script Error - An error has occurred in the script on this page Line 289 Char 1 Function Expected Code 0 URL res://ieframe.dll/preview.js

You may also get Script Error - An error has occurred in the script on this page Line 518 Char 1 Error The callee (server [not server application]) is not available and disappeared; all connections are invalid. The call did not execute. Code 0 URL res://ieframe.dll/preview.js

Create Separate Thread Which Waits 1 Second After The WebBrowser is Disposed and the calls renderThread.Abort()

Here is the code for this,

        public void TryDispose()
        {
            //
            // Do not Dispose Twice
            //

            if (_doDispose)
                return;

            _doDispose = true;

            //
            // Dispose Browser
            //

            browser.Invoke(
                new MethodInvoker
                    (
                        () =>
                        {
                            browser.Stop();

                            browser.DocumentCompleted -= HasRendered;
                            browser.Disposed += SetDisposeEvent;

                            if (browser.ActiveXInstance != null)
                                Marshal.ReleaseComObject(browser.ActiveXInstance);
                            if (browser.Handle != null)
                                Marshal.Release(browser.Handle);

                            browser.Dispose();

                        }
                    )
                );

            //
            // Hack Around - Create a Thread which Waits for 1 second before disposing the Web Browser
            //

            var browserDisposeThread = new Thread
                (
                    () =>
                    {
                        disposeEvent.WaitOne(1000);
                        Thread.Sleep(1000); // Wait to Avoid Script Error <:::::::::::::::::::::::
                        if (renderThread.IsAlive)
                        {
                            renderThread.Abort();
                            renderThread = null;
                            browser = null;

                            _applicationThreadReady.Dispose();
                            disposeEvent.Dispose();
                            if (resultEvent != null) resultEvent.Dispose();
                        }
                    }
                );
            browserDisposeThread.Name = "Browser Dispose Thread For " + renderThread.Name;
            browserDisposeThread.IsBackground = true;
            browserDisposeThread.Start();

            Console.WriteLine("TryDispose");
        }

Suggestions, Comments welcome.

Edited by _Alexander
This topic is now closed to further replies.
  • Posts

    • Tons in stock in all stores here in Norway... Doesn't seem that popular. I'm not buying either. Maybe when winter comes, but I'm not gonna waste my summer on being indoors and gaming.
    • Microsoft 365 Word gets SharePoint eSignature, now you can ditch third-party signing tools by Paul Hill Microsoft has just announced that it will be rolling out an extremely convenient feature for Microsoft 365 customers who use Word throughout this year. The Redmond giant said that you’ll now be able to use SharePoint’s native eSignature service directly in Microsoft Word. The new feature allows customers to request electronic signatures without converting the documents to a PDF or leaving the Word interface, significantly speeding up workflows. Microsoft’s integration of eSignatures also allows you to create eSignature templates which will speed up document approvals, eliminate physical signing steps, and help with compliance and security in the Microsoft 365 environment. This change has the potential to significantly improve the quality-of-life for those in work finding themselves adding lots of signatures to documents as they will no longer have to export PDFs from Word and apply the signature outside of Word. It’s also key to point out that this feature is integrated natively and is not an extension. The move is quite clever from Microsoft, if businesses were using third-party tools to sign their documents, they would no longer need to use these as it’s easier to do it in Word. Not only does it reduce reliance on other tools, it also makes Microsoft’s products more competitive against other office suites such as Google Workspace. Streamlined, secure, and compliant The new eSignature feature is tightly integrated into Word. It lets you insert signature fields seamlessly into documents and request other people’s signatures, all while remaining in Word. The eSignature feature can be accessed in Word by going to the Insert ribbon. When you send a signature request to someone from Word, the recipient will get an automatically generated PDF copy of the Word document to sign. The signed PDF will then be kept in the same SharePoint location as the original Word file. To ensure end-to-end security and compliance, the document never leaves the Microsoft 365 trust boundary. For anyone with a repetitive signing process, this integration allows you to turn Word documents into eSignature templates so they can be reused. Another feature that Microsoft has built in is audit trail and notifications. Both the senders and signers will get email notifications throughout the entire signing process. Additionally, you can view the activity history (audit trail) in the signed PDF to check who signed it and when. Finally, Microsoft said that administrators will be able to control how the feature is used in Word throughout the organization. They can decide to enable it for specific users via an Office group policy or limit it to particular SharePoint sites. The company said that SharePoint eSignature also lets admins log activities in the Purview Audit log. A key security measure included by Microsoft, which was mentioned above, was the Microsoft 365 trust boundary. By keeping documents in this boundary, Microsoft ensures that all organizations can use this feature without worry. The inclusion of automatic PDF creation is all a huge benefit to users as it will cut out the step of manual PDF creation. While creating a PDF isn’t complicated, it can be time consuming. The eSignature feature looks like a win-win-win for organizations that rely on digital signatures. Not only does it speed things along and remain secure, but it’s also packed with features like tracking, making it really useful and comprehensive. When and how your organization gets it SharePoint eSignature has started rolling out to Word on the M365 Beta and Current Channels in the United States, Canada, the United Kingdom, Europe, and Australia-Pacific. This phase of the rollout is expected to be completed by early July. People in the rest of the world will also be gaining this time-saving feature but it will not reach everyone right away, though Microsoft promises to reach everybody by the end of the year. To use the feature, it will need to be enabled by administrators. If you’re an admin who needs to enable this, just go to the M365 Admin Center and enable SharePoint eSignature, ensuring the Word checkbox is selected. Once the service is enabled, apply the “Allow the use of SharePoint eSignature for Microsoft Word” policy. The policy can be enabled via Intune, Group Policy manager, or the Cloud Policy service for Microsoft 365 Assuming the admins have given permission to use the feature, users will be able to access SharePoint eSignatures on Word Desktop using the Microsoft 365 Current Channel or Beta Channel. The main caveats include that the rollout is phased, so you might not get it right away, and it requires IT admins to enable the feature - in which case, it may never get enabled at all. Overall, this feature stands to benefit users who sign documents a lot as it can save huge amounts of time cumulatively. It’s also good for Microsoft who increase organizations’ dependence on Word.
    • It's always good to have an option to secure your stuff to another medium. I did that with DVD/CD collection, and run my own media server now. It's more convenient that way and no need for separate players anymore.
    • Google Search AI Mode gets support for data visualization and custom charts by Aditya Tiwari Google announced it is rolling out support for data visualizations and graphs for finance-related queries in Google Search's AI Mode. Introduced last month at the Google I/O 2025 keynote, the feature lets you analyze complex datasets and create custom charts simply using natural language prompts. The updated AI Mode lets you compare and analyze information over a specific period, Google explained. It generates interactive graphs and provides a comprehensive explanation for your questions. AI Mode utilizes Gemini's multimodal capabilities and multi-step reasoning approach to comprehend the question's intent while accessing historical and real-time information relevant to the question. For instance, instead of manually researching individual companies and their stock prices, you can use AI Mode to compare the stock performance of different companies for a specific year. Once the graph is generated, you can choose the desired time period using the mouse cursor and ask follow-up questions based on the data presented. These new data visualizations for finance queries are available to users who have enabled the AI Mode experiment in Labs. AI Mode was introduced earlier this year as an experimental feature in the US. The feature is an upgraded version of AI Overviews, and Google closely worked with AI power users through the initial development process. It uses the “query fan-out” technique to perform multiple related searches across subtopics and different data sources, then combines them to come up with a comprehensive response. Google updated AI Mode last month to use a custom version of the latest Gemini 2.5 model. It added several new features, including Deep Search, live capabilities, agentic capabilities of Project Mariner, a new shopping experience, and the ability to add personal context by linking Google apps. The search giant is planning to turn AI Mode into its bread and butter. It has begun testing ads for the feature, which will appear below and be integrated into AI Mode responses where relevant.
    • Guys, you should find another way to promote your deals... It's the third article in the last months that promote this deal for an upgrade from 10. Considering that upgrade from 10 to 11 is free it's a total non-sense.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      432
    2. 2
      +FloatingFatMan
      239
    3. 3
      snowy owl
      213
    4. 4
      ATLien_0
      211
    5. 5
      Xenon
      157
  • Tell a friend

    Love Neowin? Tell a friend!