最終更新日 2025-02-18

http系のリンクを外部ブラウザで開くには?

レンダリング枠やブラウザ枠で、リンクを外部ブラウザで開くには、
HttpServerオブジェクトと、openbyshell を組み合わせるのが効果的です。

HttpServerとopenbyshellを使いましょう

test.mac
jsmode "WebView2\\" + currentmacrofilename;

js {

debuginfo(2);

if (typeof(server) != "undefined") {
    server.close();
}

let global_href = "";
function openExternalBrowser() {
    openbyshell(global_href);
}

function setExternalBrowserArg(href) {
    global_href = href;
}

var server = hidemaru.createHttpServer(async (req, res) => {

    let url = req.url;
    // ここはパッチだと思って!!
    if (typeof (url) != "string") {
        url = await req.url;
    }

    if (url.startsWith("/link/")) {
        res.writeHead(200);//OK
        res.end("");

        try {
            let href = url.replace("/link/", "");

            // 以下はopenbyshellが同期関数であるために必要となってしまうpostExecMacroMemory
            setExternalBrowserArg(href);
            hidemaru.postExecMacroMemory( "js { openExternalBrowser(); }" );

        } catch(e) {
            console.log(e);
        }
    } else {
        res.writeHead(404);//Not found
        res.end("");
    }
});

server.listen(0); //ランダムなポート
let port = server.port;

if (port == 0 ) {
    console.log("サーバー構築失敗");
}

function makeUrl(htmlFullPath, port) {
    let absoluteUrl = new URL(htmlFullPath);
    let params = new URLSearchParams();
    params.set("port", String(port));
    absoluteUrl.search = new URLSearchParams(params).toString();
    return absoluteUrl;
}

function main() {

    let url = makeUrl(currentmacrodirectory() + "\\" + "test.html", port);

    renderpanecommand({
        target: "test",
        url: url,
        show: 1,
    });
}

main();


}

HTML 側

test.html
<!DOCTYPE html>
<html>
<head>
    <title>test.html</title>
</head>
<body>
    
    <div><a href="https://www.google.com">https://www.google.com</a></div>

    <script>
    // ファイルURLからポート番号を取得
    let urlParams = new URLSearchParams(window.location.search);
    let port = Number(urlParams.get('port'));
    let func = Number(urlParams.get('func'));

    document.addEventListener('click', (event) => {
        try {
            // クリックされた要素が <a> タグかどうかを確認
            const link = event.target.closest('a[href]');
            if (link) {
                const href = link.getAttribute('href');
                const target = link.getAttribute('target');
                if (href && href.startsWith('http')) {
                    openExternalBrowser(href, target);
                }
            }
        } catch (e) {
        }
    });

    function openExternalBrowser(href, target) {
        try {
            if (port) {
                fetch("http://localhost:" + port +"/link/" + encodeURIComponent(href))
                .catch(error => {
                });
            }
        } catch (e) {
            window.alert(e);
        }
    }
    </script>
</body>
</html>