2

Having a WebBrowser control, I roughly do the following steps:

  1. Navigate to "about:blank".
  2. Turn on design mode in DocumentCompleted event handler.
  3. Paste a HTML string with an # as the URL.
  4. Read the document back from the WebBrowser control.

Step 2 is done by this way:

private void webBrowser1_DocumentCompleted(
    object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    dynamic axObj = webBrowser1.ActiveXInstance;
    axObj.document.designmode = "On";
}

Step 3 is done this way:

private void button1_Click(object sender, EventArgs e)
{
    var doc = (HTMLDocument)webBrowser1.Document.DomDocument;
    var selection = doc.selection;
    var range = (IHTMLTxtRange)selection.createRange();
    range.pasteHTML("<p><a href=\"#\">Read more</a></p>");
}

Step 4 is done this way:

private void button2_Click(object sender, EventArgs e)
{
    MessageBox.Show(this, webBrowser1.DocumentText);
}

What I expect:

I would expect to get a HTML string like this:

<html><body>
    <p><a href="#">Read more</a></p>
</body></html>

What I actually get:

I get an HTML string where the # URL is prefixed with the current document's URL:

<html><body>
    <p><a href="about:blank#">Read more</a></p>
</body></html>

This happens, no matter whether I navigate to about:blank or e.g. https://www.google.com or any other URL.

My question:

Is there any way to prevent IE/mshtml/WebBrowser control from prefixing the currently loaded URL when pasting anchors?

Update 1:

A possible workaround I can think of is to paste an absolute URL like e.g. http://pseudo-hash.com instead of the # and later when getting the HTML back from the WebBrowser control do a string replace and replace the pseudo placeholder URL back with #.

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
  • 1
    I don't have time to verify, but I wonder if it happens when using `FEATURE_BROWSER_EMULATION` (e.g., like [this](https://stackoverflow.com/a/18333982/1768303)). – noseratio Jun 26 '17 at 11:40

0 Answers0