Windows 上 UWP 应用与其配套浏览器扩展之间的本机消息传递

问题描述

背景

我有一个 UWP 应用程序,它在其私有数据文件夹中写入数据。

我需要能够从浏览器扩展中读取该数据。

我目前的方法

我在我的解决方案中添加了一个新的 C++ 项目,该项目可以使用标准输入和标准输出通过我的浏览器扩展执行二进制本机消息传递。

供您参考,浏览器扩展助手的代码是

#include "pch.h"

#include <string>
#include <iostream>
#include <fcntl.h>
#include <io.h>

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif


void writeResponse(std::string response) {
    unsigned int length = response.length();
    std::cout.write(reinterpret_cast<const char*>(&length),4);
    std::cout << response << std::flush;
}

std::string readInputMessage() {
    bool hasFetchedInput = false;
    do {
        char rawInputLength[4];
        std::cin.read(rawInputLength,4);
        unsigned int inputLength = *reinterpret_cast<unsigned int*>(rawInputLength);
        if (inputLength < 1024 && inputLength>1)
        {
            hasFetchedInput = true;
            char* input = new char[inputLength];
            memset(input,inputLength + 1);
            std::cin.read(input,inputLength);
            std::string inputMessage(input);
            delete[] input;
            return inputMessage;
        }
        else {
            Sleep(1000);
        }
    } while (!hasFetchedInput);
}

std::string handleMessage(std::string inputMessage) {
    // inputMessage and response must always be stringified objects
    std::string copy = inputMessage;
    std::string response = "{\"hello\":\"world\"}";
    return response;
}

int main()
{
    _setmode(_fileno(stdin),_O_BINARY);
    _setmode(_fileno(stdout),_O_BINARY);
    std::string inputMessage = readInputMessage();
    std::string response = handleMessage(inputMessage);
    writeResponse(response);
}

(我还没有对阅读文件部分进行编码)。

此代码确实有效,并且能够在调试模式下与我的扩展程序进行通信。 为此,我还需要在注册表中添加一个键

REG ADD "HKCU\Software\Microsoft\Edge\NativeMessagingHosts\myAppBrowserExtensionHelper" /ve /t REG_SZ /d "C:\Users\me\path\to\extension_host_manifest.json" /f

有趣的文档链接:

Edge Extension Native Messaging

App to App communication 注意:这种方法似乎已经过时,因为 Edge 更改了其本机消息传递机制以匹配 Chrome 浏览器之一。至少,尽管我付出了很多努力,但我还是没能让它发挥作用。

我的问题

现在,我需要使用这个浏览器扩展助手来打包 UWP 应用程序。 我希望能够通过 Microsoft Store 和旁加载分发我的应用。

所以我正在尝试创建一个内置到 msixbundle 中的新打包程序项目,但我以前从未这样做过,我不知道应该如何做到这一点。

  • 具体来说,我如何让 msixbundle 在注册表中添加密钥(理想情况下是在安装时或在运行时)?
  • 如何确保 BrowserExtensionHelper.exe 能够读取 UWP 应用私有文件? (我在某处读到只有当 .exe 与它尝试读取的文件位于同一目录中时,这才有可能)

当然,如果您认为我做错了,请不要犹豫,提出一种新方法。

非常感谢所有愿意看这个的人。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)