边缘浏览器上的本机消息传递

问题描述 投票:0回答:1
{
  "manifest_version": 3,
  "name": "Mac Address",
  "version": "1.0",
  "description": "Mac Address",
  "permissions": [
    "activeTab",
    "nativeMessaging", 
    "tabs"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["url of product"],
      "js": ["content.js"]
    }
  ],
  "host_permissions": [
    "url of product"  
  ],
  "icons": {
    "16": "icons/icon.png",
    "48": "icons/icon.png",
    "128": "icons/icon.png"
  }
}


代码是manifest.json

const nativeHostName = 'com.example.macaddress';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "sendToNativeHost") {
    console.log("Sending message to native host:", request.data);
    chrome.runtime.sendNativeMessage(nativeHostName, request.data, (response) => {
      if (chrome.runtime.lastError) {
        console.error("Native message error:", chrome.runtime.lastError.message);
        sendResponse({ success: false, error: chrome.runtime.lastError.message });
      } else {
        console.log("Received response from native host:", response);
        sendResponse({ success: true, response });
      }
    });
    return true; // Indicates that the response will be sent asynchronously
  }
});

上面的代码是background.js

function monitorAndHandleClick() {
  const targetElement = document.querySelector('label#lblLogin.mybutton.btnPadding');

  if (targetElement) {
    console.log("Target element found:", targetElement);
    targetElement.addEventListener('click', () => {
      const dataToSend = {
        action: "sendToNativeHost",
        data: {
          url: window.location.href,
          elementId: targetElement.id,
          timestamp: new Date().toISOString()
        }
      };
      console.log("Sending message to background script:", dataToSend);
      chrome.runtime.sendMessage(dataToSend, (response) => {
        if (response && response.success) {
          console.log("Message sent to native host successfully.");
        } else {
          console.error("Failed to send message to native host:", response);
        }
      });
    });
  } else {
    console.error("Target element not found.");
  }
}

if (window.location.href === 'url of product') {
  console.log("Target URL matched, starting click monitoring.");
  monitorAndHandleClick();
}

以上代码content.js.

以上所有代码在 Chrome 浏览器(131.0.6778.205)上运行良好,但在边缘(131.0.2903.112)上运行不佳。我现在可以知道错误在哪里吗?我在注册表中的路径为 reg

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Edge\NativeMessagingHosts\com.example.macaddress

.

当上面的代码在 chrome 浏览器上工作正常但在 Edge 上不行时,我能知道问题出在哪里吗?

javascript registry chrome-native-messaging microsoft-edge-extension
1个回答
0
投票
我建议参考

调试本机消息传递来调试您的扩展/主机。可以添加

--enable-logging=stderr --v=1
作为启动 Microsoft Edge 时的命令行选项。找出错误后,您可以按照同一部分下的常见错误和提示进行操作。

© www.soinside.com 2019 - 2024. All rights reserved.