我创建了一个简单的测试网页,使用以下示例来向本机应用程序发送数据和从本机应用程序接收数据:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging
使用Vue创建网络:
<template>
<div>
Enter Message: <input id="message"></input>
<button id="ping" type="button">Ping!</button><br/>
Output message: <span id="output"></span>
</div>
</template>
<script>
export default {
}
</script>
插件background.js
/*
On startup, connect to the "ping_pong" app.
*/
var port = browser.runtime.connectNative("ping_pong");
/*
Listen for messages from the app.
*/
port.onMessage.addListener((response) => {
console.log("bg Received: " + response);
browser.tabs.query({
currentWindow: true,
active: true
}).then(sendMessageToTabs.bind(null, response))
});
browser.runtime.onMessage.addListener(notify);
function notify(message) {
console.log("bg Sending: ping" + message);
port.postMessage("Received and returned message: " + message);
}
function sendMessageToTabs(message, tabs ) {
console.log("bs message:");
console.log(message);
console.log("bs tabs:");
console.log(tabs);
for (let tab of tabs) {
browser.tabs.sendMessage(
tab.id,
{message}
);
}
}
和contentScript.js
console.log("Content script found!");
if (document.getElementById("ping")) {
document.getElementById("ping").addEventListener("click", notifyExtension);
}
function notifyExtension(e) {
console.log("cs Clicked!");
console.log("cs sending " + document.getElementById("message").value);
browser.runtime.sendMessage(document.getElementById("message").value);
}
browser.runtime.onMessage.addListener(notify);
function notify(message) {
console.log("cs Received; ");
console.log(message);
document.getElementById("output").innerHTML = message.message;
}
我的问题是,我们如何使Vue接收返回的数据以能够使用它,进行处理等...我的意思是将其保存在vue数据变量中。
谢谢!
答案 0 :(得分:1)
在Vue组件中,使用计算属性返回消息的值,而计算属性监视更改并相应地进行更新。
例如:
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
name: 'MyComponent',
computed: {
message() {
return window.message // or whatever the variable is
}
}
}
</script>