gpt4 book ai didi

javascript - 如何将信息从 Content_script 传递到弹出页面? (Chrome 扩展)

转载 作者:行者123 更新时间:2023-11-30 18:46:10 24 4
gpt4 key购买 nike

我想将一个已保存的变量从内容脚本传递到弹出页面,这样我就可以简单地输出它。例如,如果我的内容脚本具有以下代码:

var x = 'abc';

我希望弹出窗口标题如此可变。

最佳答案

有几种方法可以做到这一点,我在我的扩展中使用了第一种方法:

  1. 本地存储。使用 sendRequest({}) 将带有变量的消息传递到后台页面,然后后台页面会将变量保存到 localStorage。完成后,您的弹出窗口可以访问变量,如 localStorage["x"]。 (必须通过后台页面,因为此时内容脚本无法访问localStorage)

  2. 简单的请求。祈祷弹出窗口打开,并尝试从内容脚本向它发送一条消息,其中包含变量。请注意,这不是一个好的解决方案,因为当您尝试向它发送变量时,弹出窗口可能不会打开。

#1 的代码示例:

//sendRequests look like this: sendRequest(message - Object, [callback - Function]);

//API Docs:
//onRequest Listener: http://code.google.com/chrome/extensions/extension.html#event-onRequest
//sendRequest Method: http://code.google.com/chrome/extensions/extension.html#method-sendRequest
//localStorage: http://www.html5rocks.com/features/storage

//From the Content Script
//Send request to background.html, no callback

chrome.extension.sendRequest({
type: "popup_var", /* In my extensions, because I could often be different types of reqeusts, I use a type variable to identify them */
my_variable: "Sally sold seashells by the seashore" /* Whatever variable you are trying to send */
});

//In background.html

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse){
if(request.type == "popup_var"){
/* The type of message has been identified as the variable for our popup, let's save it to localStorage */
localStorage["popup_var"] = request.my_variable;
}
}
);

//In popup.html

console.log( "Variable from Content Script: "+localStorage["popup_var"] );

关于javascript - 如何将信息从 Content_script 传递到弹出页面? (Chrome 扩展),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377163/

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