andyabel
andyabel

Reputation: 344

C# Open URL targeting a specific tab

I have a C# WinForms application that has click-thoughs to a web application. In the C# application whenever someone clicks on a link for Campaign#123 I want it to open in the same browser tab (the tab for #123). And when they click on a link for Campaign#456 I want it to open in in a different tab (the tab for #456).

In HTML you can specify the tab using the target=framename option like this. And this does exactly what I want:-

<a target=456 href="https://www.w3schools.com">Visit W3Schools</a>

So how do I pass the "target=456" part to the Process.Start() interface? Or is there some other interface I should use to open a URL with a target?

System.Diagnostics.Process.Start(url);

Thanks

Upvotes: 1

Views: 1737

Answers (1)

CodeCaster
CodeCaster

Reputation: 151604

Using System.Diagnostics.Process.Start(url), you're asking the OS to open the associated application for a given HTTP(S) URL (a "protocol handler"). You don't know which associated application is registered nor how it would support passing the target name along with the URL, let alone no browsers that I know of supporting that (Chrome for one doesn't, it lacks a --target command-line switch).

What you can do, is pass the target URL and target to a small web page which opens the link and closes itself:

<!DOCTYPE html>
<html>
  <body>
    <a id="theLink"></a>
  </body>
  <script type="text/javascript">
    // https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }
    
    var anchor = document.getElementById("theLink");
    
    anchor.target = getParameterByName("target");
    anchor.href = getParameterByName("href");
    anchor.title = getParameterByName("title");
    anchor.innerText = anchor.title;

    // Go there
    anchor.click();
    
    // Close us
    window.close();
  </script>
</html>

Now you can call it like openintarget.html?href=http://google.com&target=1234&title=Foo.

However, browsers don't like what this page does. First, you'll have to accept it can show popups (it doesn't, but probably a blanket name for code that generates links and clicks it). Next, you can't close a tab from JavaScript which you didn't open from JavaScript, so now you have a new problem: the appropriate target tab gets reused, but this HTML page stays open, and worse, focused.

So I don't think you can do this. Perhaps hosting a web browser within your application is viable? That could allow more control over visible tabs.

Upvotes: 5

Related Questions