我在想,如果我有一个Chrome扩展程序,当你点击图标时会弹出一个弹出窗口,并且该弹出窗口有一个文本框,用于输入数据,那么获取文本框内文本的Javascript代码会是什么样子?
更新:我知道如何从文本框中获取值,但我的问题是,我如何具体访问popup.html文件中的元素?我尝试访问document.getElementById等等,但这些获取的是实际页面内容中的元素,而不是我的自定义弹出窗口。
我在想,如果我有一个Chrome扩展程序,当你点击图标时会弹出一个弹出窗口,并且该弹出窗口有一个文本框,用于输入数据,那么获取文本框内文本的Javascript代码会是什么样子?
更新:我知道如何从文本框中获取值,但我的问题是,我如何具体访问popup.html文件中的元素?我尝试访问document.getElementById等等,但这些获取的是实际页面内容中的元素,而不是我的自定义弹出窗口。
我们可以通过绑定事件监听器获取弹出页面文本框中的值,例如在按钮的点击事件中按以下方式进行:
假设 manifest.json 文件如下:
{
"manifest_version": 2,
"name": "Wonderful extension",
"description": "Wonderful extension - gets value from textbox",
"version": "1.0",
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "popup.html"
}
}
并且popup.html的内容如下:
<!DOCTYPE html>
<html>
<head>
<title>Wonderful Extension</title>
<script src="popup.js"></script>
</head>
<body>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>Please enter your name : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html>
然后我们可以按照以下方式绑定文档中的事件,以获取文本框中的值:
文件 popup.js :
document.addEventListener('DOMContentLoaded', documentEvents , false);
function myAction(input) {
console.log("input value is : " + input.value);
alert("The entered data is : " + input.value);
// do processing with data
// you need to right click the extension icon and choose "inspect popup"
// to view the messages appearing on the console.
}
function documentEvents() {
document.getElementById('ok_btn').addEventListener('click',
function() { myAction(document.getElementById('name_textbox'));
});
// you can add listeners for other objects ( like other buttons ) here
}
要访问弹出页面的其他元素,我们可以使用类似的方法。
同样可以这样使用chrome.storage.sync:
function handleButtonClick(){
// Use stored sync value.
chrome.storage.sync.get("textBoxValue", ({ textBoxValue }) => {
alert(textBoxValue);
});
}
document.getElementById("popupButton").addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Store sync value before the script is executed.
let textBoxValue = document.getElementById('textBox').value;
chrome.storage.sync.set({ textBoxValue });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: handleButtonClick,
});
});
prompt
吗? - Elias Van Ootegem$(“input [type ='text']”).change(function(){console.log($(this).val())});
。 - Stan