Giter VIP home page Giter VIP logo

Comments (2)

hehehai avatar hehehai commented on May 26, 2024

消息传递

chrome extension onMessage, sendMessage 不支持直接异步,使用时需要注意 ref

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting === "hello")
      setTimeout(() => sendResponse({farewell: "goodbye"}), 1000)
  }

  // return true
);

直接使用,这里 sendMessage 的 response 是拿不到响应的,原因是 onMessage 的响应处理是同步的,这里在 setTimeout 的处理时,通信已关闭了,解决方法是:return true 表示惰性关闭,在sendReponse 后关闭。

这里也无法直接将 linsten 函数设置为异步,里面仅可使用 Promise then 的方式

from cratehub.

hehehai avatar hehehai commented on May 26, 2024

工具使用 webext-bridge

webext-bridge 内部维护了通信序列,管理各端口(background, options ...) 的通信,也做了兼容处理

async () => {
    const res = await sendMessage(
      "get-preferences",
      { sync: false, name: 'hehehai' },
      "background"
    )
    console.log(res)
  }

onMessage<{ name: string; sync: boolean }, "get-preferences">(
  "get-preferences",
  async ({ data }) => {
    console.log(data)
    const res = await fetch(`https://api.github.com/users/${data.name}`)
    return await res.json()
  }
)

这里要设置 sync: false

from cratehub.

Related Issues (19)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.