gpt4 book ai didi

javascript - 来自 DOM chrome 扩展的 JS 变量

转载 作者:行者123 更新时间:2023-12-03 09:17:37 26 4
gpt4 key购买 nike

我想使用注入(inject)脚本将一些 js 变量放入 DOM 中。为此,我有两个文件,一个将脚本注入(inject) DOM,另一个文件发送值。

getPageSource.js

var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};

function getTag(){
document.addEventListener('ITAG_connectExtension', function(e) {
return e.detail;
});}

chrome.extension.sendMessage({
action: "getSource",
source: getTag()
});

脚本.js

var tagType = {};
tagType = itsClickPI;
setTimeout(function() {
document.dispatchEvent(new CustomEvent('ITAG_connectExtension', {
detail: tagType
}));
}, 0);

但是 popup.js 中的 request.source 未定义。

popup.js

chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});

你能给我一些灯吗?

提前致谢。

最佳答案

您的问题出在 getTag() 函数上 - 它是 asynchronous and cannot possibly return e.detail.

即使这样,逻辑也是可疑的 - 您正在添加一个事件监听器,但您在它之前触发了该事件。

那么预期的流程是什么?

  1. 准备好接收回复。
  2. 注入(inject)一个发送数据的脚本(我们已准备好接收数据)。
  3. 将该数据发送到其他地方。

正确的事件链是这样的:

function sendTag(tag) {
// chrome.extension.sendMessage / onMessage are deprecated!
chrome.runtime.sendMessage({
action: "getSource",
source: tag
});
}

// 1. Get ready to listen
document.addEventListener('ITAG_connectExtension', function(e) {
// This code executes asynchronously only when the event is received, so:
// 3. Send the data
sendTag(e.detail);
});

// 2. Inject the script
var s = document.createElement('script');
s.src = chrome.extension.getURL('script.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
s.parentNode.removeChild(s);
};

如果需要多次执行,只需再次注入(inject)脚本(因为监听器已准备好)。

再次在接收端使用chrome.runtime.onMessage

关于javascript - 来自 DOM chrome 扩展的 JS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918578/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com