原理很简单,通过 websocket 通信 https://github.com/inu1255/debugirl
简单写了个服务端,可以获取 V2EX 的用户名。 可以看到跟写 chrome 插件的体验基本一致。
async function start() {
let tabs = await chrome.tabs.query({
url: "https://www.v2ex.com/",
});
let tab = tabs[0];
if (!tab) {
tab = await chrome.tabs.create({
url: "https://www.v2ex.com/",
index: 0,
active: false,
});
}
if (tab.status != "complete") await waitComplete(tab);
let name = await chrome.scripting.executeScript({
target: {tabId: tab.id},
func: function () {
return document.querySelector(".bigger").innerText;
},
});
console.log("your V2EX username is:", name);
}