在这里问了 2 个问题后,我终于完善了我的 Chrome 扩展程序。我正在根据教程站点的示例制作它供个人使用,我的版本旨在从用户那里获取查询输入,转到 Flickr 的 API 并通过搜索该查询返回 24 张图像。我打开了页面,嗯,一个页面,它工作得很好。但是当我尝试将其作为扩展打开时,无论用户输入什么,查询词都不会改变。因此,我得出的结论是,Chrome扩展程序不支持某些代码,或者我正在做一些可怕的错误。如果前者是正确的,您能否指定我可以和不能在扩展中使用的内容(或将我链接到有答案的地方)?注意:是的,我知道服务器端语言不能完全工作。但是,如果是我在做傻事,请告诉我,如果可能的话,帮我解决这个问题。提前感谢您提供的任何帮助。代码如下:
JS(弹出窗口.js):
var q = "cake"; //Default search term
var req;
function querySubmit() {
oForm = document.forms["queryForm"];
oText = oForm.elements["query"];
q = oText.value
document.getElementById("images").innerHTML = "";
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=" + q + "&" +
"safe_search=1&" +
"content_type=1&" +
"sort=relevance&" +
"per_page=24",
true);
req.onload = showPhotos;
req.send(null);}
var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=" + q + "&" +
"safe_search=1&" +
"content_type=1&" +
"sort=relevance&" +
"per_page=24",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
var photos = req.responseXML.getElementsByTagName("photo");
for (var i = 0, photo; photo = photos[i]; i++) {
var a = document.createElement("a");
a.setAttribute("href",constructImageURL(photo));
a.setAttribute("target","_blank");
var img = document.createElement("img");
img.setAttribute("src",constructImageURL(photo));
a.appendChild(img);
document.getElementById("images").appendChild(a);
}
}
function constructImageURL(photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
HTML (popup.html):
<!DOCTYPE html>
<html>
<head>
<title>Teh popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
<div id="images">
</div>
<form name="queryForm" onsubmit="querySubmit();return false" action="#">
Search: <input type='text' name='query'>
<input type="submit" />
</form>
</body>
</html>
manifest.json:
{
"name": "Flickr image searcher",
"version": "1.0",
"manifest_version": 2,
"description": "Searches images on Flickr wirtout opening another page.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "results.html"
},
"permissions": [
"http://api.flickr.com/"
]
}
HTML 中的onsubmit
处理程序是内联 JavaScript,这在 manifest_version: 2
中是不允许的。
相反,请使用 JS 文件中的addEventListener
将 submit
事件处理程序函数绑定到窗体:
theForm.addEventListener("submit", function() {
//...
return false; // stop submission
});