【问题标题】:How do i get the local storage value in background page?如何在后台页面中获取本地存储值?
【发布时间】:2011-08-04 06:31:19
【问题描述】:

就开发 chrome 扩展而言,我是新手。

我正在测试一个扩展。在这个我有一个背景页面和选项页面。在选项页面中,我将用户输入的密码存储在本地存储中,我想在点击浏览器图标的背景页面中检索该密码。

我的选项页面是:

<html>
<head>
<title>Options for Password</title>
<script>
 function savePassword()
  {
 window.localStorage.setItem('password', txtPassword.value);


  }
</script>   
</head>
<body >
<h1>Enter Password</h1>
<input type='password' name='txtPassword' id='txtPassword'/>
<br />
<button onclick='savePassword();'>Save</button>
<br />
</body>
</html>

而我的后台页面是:

<html>
<head>
<script>
 // Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {code:"alert('password from tab:'+window.localStorage.getItem('password'));getfeedback_dialog_submitButton.setAttribute('onclick', 'if(gettext.value==\'"+window.localStorage.getItem(password)'+"\'){document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);}');"});
});


</script>
</head>
</html>

当我通过选项页面保存密码然后点击浏览器操作时,我会收到警报 password from tab:null

我很困惑如何检索存储在本地存储中的值?

【问题讨论】:

    标签: google-chrome google-chrome-extension local-storage


    【解决方案1】:

    您的代码从单击浏览器操作的页面获取 localStorage 值,该值是null。更改您的报价以在后台页面获取它:

    chrome.tabs.executeScript(null, {code:"alert('password from tab:"+window.localStorage.getItem('password')+"');"});
    

    请注意,这可能允许代码注入。

    编辑:这样做,只要你的变量被正确定义并且window.localStorage.getItem('password')应该是一个字符串,它就应该工作:

    chrome.tabs.executeScript(null, {code:"alert('password from tab:"+window.localStorage.getItem('password')+"');"
    +"getfeedback_dialog_submitButton.addEventListener('click', function(event){if(gettext.value=='"+window.localStorage.getItem('password')+"')"
    +"{document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);}},false);"});
    

    为了便于阅读,我将您的代码分成多行。

    【讨论】:

    • 感谢数码回复。你能帮我看看我想测试存储的值是否等于某个文本框输入的值吗?我必须测试以下条件 if(gettext.value==window.localStorage.getItem(password)){document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);} 我怎样才能在这段代码中写这个块?
    • @Pankaj Khurana 如果您还要注入代码,只需执行if(gettext.value==\'"+window.localStorage.getItem(password)'+"\'){... 但我会推荐使用message passing 的外部脚本。
    • 我使用了以下代码,但没有发生任何事情,我错过了什么(没有错误):getfeedback_dialog_submitButton.setAttribute('onclick', 'if(gettext.value==\'"+window.localStorage. getItem(password)'+"\'){document.body.removeChild(getfeedbackcontainer);document.body.removeChild(getfeedbackoverlay);}');"});
    • onclick 在页面上下文中运行,而不是在内容脚本的上下文中运行,您的引用可能不起作用。但是您可以在另一个问题中提出这个问题或编辑您的问题吗?
    • 我已经编辑了我的问题并添加了检查用户输入是否等于存储值的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多