我如何能够访问在内容脚本的选项页上设置的数据,例如。在谷歌浏览器扩展 [英] How could i achieve to access the data which where set on options page in the content script eg. in the google chrome extension
问题描述
我在选项页面设置了一些值。这现在工作正常。但我无法访问在background.html或内容脚本中设置的数据。我已经阅读过类似这样的消息,但对我来说有点难以理解。如果有人能指出我朝着正确的方向发展,那会很好。
示例故事>
我在选项页面设置此值 localStorage.setItem(somedata,true);
然后,如果我将访问相同的数据在网页上的扩展将运行我得到它是这样的:
localStorage。的getItem( somedata);
值为 null
。内容脚本不能直接从背景页面读取localStorage值。 如果您想阅读localStorage键值对,请参阅此答案,其中提供了一个说明以及用于实现此目的的代码:
虽然前面的方法可行,但我推荐 下面是一个例子来说明dfference: 一见钟情, I am setting some values at the option page. This is now working okay. But i am unable to access the data setted in the background.html or in the content script. I have read that something like this is possible with messaging but for me is the documentation a little bit hard to understand. If someone could point me out in the right direction it would be good.
Example story>
I am setting this value at the options page And the value is Content scripts cannot directly read the localStorage values from the background page. If you wish to read localStorage key-value pairs, see this answer which provides an explanation plus code for achieving this: Accessing global object from content script in chrome extension Although the previous method works, I recommend the Here's an example to illustrate the dfferences: On the first sight, the 这篇关于我如何能够访问在内容脚本的选项页上设置的数据,例如。在谷歌浏览器扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! chrome.storage
API相反:这可以被所有的扩展页面使用。 localStorage
和 chrome.storage
之间的巨大差异在于 chrome.storage $ c
是一个异步 API。
//同步localStorage
localStorage.setItem('keyname','value');
alert(localStorage.getItem('keyname'));
//异步chrome.storage
chrome.storage.local.set({keyname:'value'},function(){
chrome.storage.local.get( 'keyname',function(items){
alert(items.keyname);
});
});
chrome.storage
API看起来更复杂。但是,如果您想要将数据保存到扩展中,这是最好的方式。 localStorage
方法需要更多的代码(请参阅我在这个答案上链接的答案)来实现相同的功能。而且,也是异步的。localStorage.setItem("somedata" , "true");
Then if i would access the same data on the page where the extension would be to run i get it like this:localStorage.getItem("somedata");
null
. chrome.storage
API instead: This can be used by all extension pages. A huge difference between localStorage
and chrome.storage
is that chrome.storage
is an asynchronous API.// synchronous localStorage
localStorage.setItem('keyname', 'value');
alert(localStorage.getItem('keyname'));
// asynchronous chrome.storage
chrome.storage.local.set({keyname: 'value'}, function() {
chrome.storage.local.get('keyname', function(items) {
alert(items.keyname);
});
});
chrome.storage
API looks more convoluted. However, if you want to save data within an extension, it's the best way to do so. The localStorage
approach takes much more code (see the answer I linked on top of this answer) to achieve the same functionality. And, it's also asynchronous.