这个问题是一种具体的问题。因此,我会尽力做到尽可能彻底。
我这样做是为了尝试学习如何制作可以与网站交互的 Chrome 扩展程序。
这应该做的是获取输入字段的输入,即用户写入的内容,然后用该文本替换网站的特定部分。我正在使用 Message Passing 中描述的“简单一次性请求” ,因为它有一个 ID,并且可以通过 getElementById
轻松编辑。
简单地替换按钮单击时的“简单一次性请求”句子很容易,但是当我尝试获取用户的输入并将其插入文档中时,就会出现问题。
这是我的代码:
manifest.json:
{
"manifest_version": 2,
"name": "document-editor-test",
"version": "1.0",
"permissions": [
"activeTab",
"cookies",
"storage"
],
"browser_action": {
"default_title": "Site Text Editor",
"default_popup": "menu.html"
}
}
content.js:
document.getElementById('button').addEventListener('click', function (evt) {
var inputText = document.getElementById('input').value;
var theValue = inputText;
chrome.storage.local.set({'value': theValue}, function(){
message('value saved');
});
chrome.tabs.executeScript({ file: 'replace.js' })
}, false);
replace.js:
var item = chrome.storage.local.get(null, function(){
message('Value gotten')
})
document.getElementById('simple').innerHTML = item;
menu.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<style>
body {width: 200px;}
#text{ font-size: 13px; text-align: center;}
</style>
<body>
<input id='input' type="text" placeholder="Text Here">
<button id='button' class='button button'>Ok</button>
<script src="content.js"></script>
</body>
</html>
我尝试使用一个简单的存储脚本来保存值并通过文件解析它,但它只会使脚本打印出undefined
。
将输入值传递到文档的解决方案是什么?
最佳答案
扩展弹出窗口是一个不同的页面,与选项卡中打开的网页无关:您的弹出脚本名称具有误导性/错误:它不是内容脚本,请将其重命名为例如
menu.js
接受函数回调的 Chrome API 方法有 asynchronous并返回函数回调中的值。检查documentation查看可能的参数。
内容脚本中的chrome.storage.local.get
调用不正确,因此按设计返回undefined
,请指定键名称并使用回调内的值:var item; chrome.storage.local.get('value', function(data) { item = data.value; document.getElementById('simple').innerHTML = item; });
弹出窗口中的代码可能会导致异步 API 中出现竞争条件,因此内容脚本会在保存值之前注入(inject)(理论上是可能的)。通过嵌套链接调用:
chrome.storage.local.set({'value': theValue}, function() { message('value saved'); chrome.tabs.executeScript({ file: 'replace.js' }); });
关于javascript - 在 Chrome 扩展中的 JavaScript 文件之间传输用户的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42047716/