我现在正在尝试创建我的第一个 Chrome 扩展程序。这是一个简单的弹出窗口,里面有许多树懒的图片。我想做的是,当您单击树懒的图片时,它会将图像 URL 附加到内容页面中的当前文本字段中。
这是我的 JSON:
{
"manifest_version": 2,
"name" : "Instant Sloth",
"description": "One button, many sloth.",
"version": "1",
"permissions": [
"https://secure.flickr.com/"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [{
"js": ["jquery.min.js", "tab.js", "jquery-ui.min.js", "input.js"],
"matches": ["http://*/*", "https://*/*"],
"run_at": "document_end"
}]
}
其中 popup.html 是包含树懒图片的 HTML 文件,input.js 是我希望能够添加交互性的脚本,如下所示:
$("img").click(function(){
var form = $(document.activeElement);
var sloth = $(this).attr('src');
form.value = (form.value + " " + sloth);
});
我在尝试弄清楚如何访问同一脚本中的内容页面和弹出窗口的元素时遇到困难。我还有链接到 pop-up.html 的 input.js 文件。感谢您的帮助!
最佳答案
此页面可能会回答很多问题:Architecture Overview
简而言之,您无法在一个脚本中执行此操作,因为弹出窗口和当前打开的页面是不同的上下文。您需要弹出窗口中的一个脚本来处理点击并获取源 URL、页面中的一个脚本 (Content Script ) 来插入文本,以及两者之间某种形式的通信。
一种方法是使用Messaging ,其中内容脚本监听来自弹出窗口的命令。这种方法是有效的,但有一个我描述的小问题here :不能 100% 保证内容脚本在给定选项卡中实际上已准备就绪。
就您而言,构建一个简短的代码片段和inject it into the page programmatically要容易得多。 .
// Popup code
$(document).ready(function() {
$("img").click(function() {
var sloth = $(this).attr('src');
var script = 'var form = document.activeElement;' +
+ 'form.value = (form.value + " ' + sloth + '");';
chrome.tabs.executeScript({code : script});
});
});
附注您将需要 "activeTab"
permission在您的 list 中才能使其发挥作用。
关于javascript - Chrome 扩展程序 : Insert text into textfield when clicking button in pop-up,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515557/