javascript - Chrome 扩展程序:在执行其他功能之前等待 sendMessage 响应?
问题描述
我的上下文菜单扩展中有两个功能。我必须单击一个才能向内容脚本发送消息,然后我必须单击另一个,因为 sendMessage 函数在我的后台脚本中设置了变量。我想要做的只是让它们成为一个按钮并让 sendMessage 函数首先返回,然后另一个函数可以做到这一点,因为现在变量已设置。这就是我的意思:
在后台.js
chrome.contextMenus.create({
title: "Send Message",
contexts: ["all"],
onclick: sendMessage
});
chrome.contextMenus.create({
title: "Get All",
contexts: ["all"],
onclick: getAll
});
var title;
var link;
var bp;
var imgSrc;
function sendMessage() {
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
req: "request"
}, function (response) {
console.log("responded");
title = response.title;
link = response.link;
bp = response.bp;
imgSrc = response.imgSrc;
});
});
};
function getAll(info) {
var el = document.createElement('textarea');
var all =
"<tr><td><img src=\"" + imgSrc + "\"></td>\n\
<td><span class =\"productTitle\">" + title + "</span></td>\n\
<td>" + bp.split("\n").slice(0, 5).map(i => '<span class="bulletPoints"><i class="fas fa-check" style="color: #5cb85c"></i> ' + i.substring(0, 90) + "...</span>").join("\n") + "</td>\n\
<td>[boombox_button tag_type=\"a\" type=\"success\" url=\"" + info.pageUrl.substring(0, link.indexOf("dp") + 14) + "\" target=\"blank\"]Check Price[/boombox_button]</td></tr>";
el.value = all;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
}
在 content.js 中
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.req == "request")
sendResponse({
title: document.getElementById("productTitle").innerText,
link: window.location.href,
bp: document.getElementById("feature-bullets").innerText,
imgSrc: document.getElementById("imgTagWrapperId").getElementsByTagName('img')[0].src.toString().replace(/_.*_/, '_SX250_')
});
return true;
});
我对 Javascript 还是很陌生,并且一直在尝试不同的东西,比如回调、承诺、setTimeout,我不确定我是否正确设置它们,但我希望有人能指出我正确的方向。
解决方案
推荐阅读
- node.js - 如何用字符串中的另一个子字符串替换所有出现的子字符串?
- python - 无法安装 postgres_copy 模块
- javascript - 带有子节点的花式树lazyLoad事件处理程序
- regex - 如何在每个涉及括号 ${ 的文件中查找模式
环境: bash(cygwin)
我需要 grep 具有特定扩展名的目录中的每个文件,并打印到屏幕上,这正是我正在寻找的模式。
它必须支持文件的每行多个模式。
模式是:美元符号,左花括号,然后是任何单词或没有单词,然后是右花括号,如下所示:
$P{<anyword>}
- yocto - 将 systemctl 命令添加到 yocto 图像
- python - 添加单个python散景标签
- javascript - dygraphs 使用动态最大值反转 y 轴(较低值)
- google-admin-sdk - 通过 google-apis 将成员添加到 google 组
- mysql - Mysql 与 Flask python 3.7 的连接出现了一些问题
- r - 仅将函数应用于嵌套列表中的数字列并在 R 中返回嵌套列表