I have finally perfected my extension for Chrome, after asking 2 questions here. I am making it for personal use, based on an example one from a tutorial site, and what my version is meant to do is take a query input from a user, go to Flickr's API and return 24 images by searching that query. I opened the page as, well, a page, and it works perfectly. But when I try to open it as an extension, whatever the user types in, the query term doesn't change. I have therefore come to the conclusion that either some code isn't supported in chrome extensions or I'm doing something horribly wrong. If the former is correct, could you please specify what I can and can't use in extensions (or link me to somewhere that has the answer)? Note: yes, I do know that server-side languages don't work altogether. If, however, it is I that is doing something stupid, please tell me and, if possible, give me a hand in fixing this. Thanks in advance for any help offered. The code is below:
JS (popup.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/"
]
}
Your onsubmit handler in your HTML is inline JavaScript, which is not allowed in manifest_version: 2.
Instead, use addEventListener in your JS file to bind a submit event handler function to your form:
theForm.addEventListener("submit", function() {
//...
return false; // stop submission
});
Related
I've been working on a NodeJS login/register script (called LoginRegister.js) that seemed to work fine in the terminal. I've also installed NodeJS, and the bcrypt module for it. Here's the file:
// Initialization
var fs = require("fs");
var bcrypt = require("bcrypt");
var LUinputID = $("#LUsernameIn").value;
var LPinputID = $("#LPasswordIn").value;
var RUinputID = $("#RUsernameIn").value;
var RPinputID = $("#RPasswordIn").value;
var UserStorageTextFile = "Users.txt";
$(document).ready(function(){
console.log("Hello");
var RButton = $("rBTN").addEventListener("click", registerUser(UserStorageTextFile, RUinputID, RPinputID));
var LButton = $("#lBTN").addEventListener("click", registerUser(UserStorageTextFile, LUinputID, LPinputID));
});
// Defining Functions
function encrypt(passwordFromUser) {
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(passwordFromUser, salt);
return hash;
}
function passCheck(passwordFromUser, passHashed){
return bcrypt.compareSync(passwordFromUser,passHashed);
}
function loginUser(usersTextFile, username, password){
data = fs.readFileSync(usersTextFile).toString();
if(data.indexOf(username) != -1){
console.log(data.indexOf(username));
for (var i = 0; i <= data.indexOf(username); i++) {
if (i == data.indexOf(username)) {
i += (username.length + 1);
passcode = data.slice(i, i+60);
if (passCheck(password, passcode)) {
console.log("Yes!!");
}
else{
console.log("No!!");
}
}
}
}
else{
console.log("No!!");
}
}
function registerUser(usersTextFile, username, password) {
data = fs.readFileSync(usersTextFile);
saveData = data + username + "-" + encrypt(password) + "\n";
fs.writeFile('Users.txt', saveData, (err2) => {
console.log("User " + username + " Registered!");
});
}
I wanted to test it in a browser, so I put together an html file to display my JS one in action:
<!DOCTYPE html>
<html>
<head>
<title>Authentication Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="LoginRegister.js"></script>
</head>
<h2>Login</h2>
<input type="text" id="RUsernameIn">
<input type="password" id="RPasswordIn">
<button id="lBTN">Login</button>
<h2>Register</h2>
<input type="text" id="LUsernameIn">
<input type="password" id="LPasswordIn">
<button id="rBTN">Register</button>
</html>
I opened up the HTML file in Microsoft Edge and tried pressing the register button after putting in details into the boxes, but I checked the Users.txt file and nothing had happened. After looking at the F12 Developer Tools, I noticed that on startup, the console stated:
SCRIPT5009: 'require' is undefined
LoginRegister.js (2,1)
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See browserify or webpack if you wish to serve browser-specific modules from Node.
See more: require is not defined? node.js
Thank Rob Raisch.
Hi,
I'm developing scorm based project, I've to play the scorm 2004 packages. courses are playing and capturing the data working properly with the using of LMS functions(LMSFinish(), commit()..etc). Now I've to implement one more function i.e RESUME the package where user left last time.
Sample cmi data
scoid:"1234"
data[cmi.completion_status]:"incomplete"
data[cmi.exit]:"suspend"
data[cmi.location]:"page3"
Hope you help.
Commonly 'cmi.suspend_data' is used so you can store a string (JSON, or other delimiter format if you want or need structure) to resume answers.
'cmi.location' has 1000 characters for you to also store a string and it can be as simple as "3" or "page3" as you have it.
Your navigation in your content presentation/player would need to be able to respond to having a location to go to. And you can use the suspend_data to put student answers back the way they were when they left.
How you decide if you are 'resuming' is a little tricky since anything except 'cmi.entry' = 'ab-initio' is a resume. Some LMS systems return blank or 'resume' so then you know to fetch your 'cmi.location' and 'cmi.suspend_data' if you use it.
This is all code you have to write, or you can read up a bit on my Wiki.
https://github.com/cybercussion/SCOBot/wiki.
I had some workaround for resume and is working for me . I saved suspended_data and then retrieved that data so player resumed for that position .
#kishor-koshti
How did you do that, I mean, tell the player to resume from a given position?
I'm being able to capture the suspended_data but I don't know how to set it back the next time I launch that course.
The API object that I have on javascript seems to be read only.
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<style>
body { margin: 0; }
</style>
<script type="text/javascript">
var API = {};
function setupScormApi() {
API.LMSInitialize = LMSInitialize;
API.LMSGetValue = LMSGetValue;
API.LMSSetValue = LMSSetValue;
API.LMSCommit = LMSCommit;
API.LMSFinish = LMSFinish;
API.LMSGetLastError = LMSGetLastError;
API.LMSGetDiagnostic = LMSGetDiagnostic;
API.LMSGetErrorString = LMSGetErrorString;
}
function LMSInitialize(initializeInput) {
console.log("LMSInitialize: " + initializeInput);
// invokeCSharp("LMSInitialize: " + initializeInput);
return true;
}
function LMSGetValue(varname) {
console.log("LMSGetValue: " + varname);
//invokeCSharp("LMSGetValue: " + varname);
return "";
}
function LMSSetValue(varname, varvalue) {
console.log("LMSSetValue: " + varname + "=" + varvalue);
// invokeCSharp("LMSSetValue: " + varname + "=" + varvalue);
return "";
}
function LMSCommit(commitInput) {
console.log("LMSCommit: " + commitInput);
// invokeCSharp("LMSCommit: " + commitInput);
return true;
}
function LMSFinish(finishInput) {
console.log("LMSFinish: " + finishInput);
// invokeCSharp("LMSFinish: " + finishInput);
return true;
}
function LMSGetLastError() {
console.log("LMSGetLastError: ");
// invokeCSharp("LMSGetLastError: ");
return 0;
}
function LMSGetDiagnostic(errorCode) {
console.log("LMSGetDiagnostic: " + errorCode);
// invokeCSharp("LMSGetDiagnostic: " + errorCode);
return "";
}
function LMSGetErrorString(errorCode) {
console.log("LMSGetErrorString: " + errorCode);
// invokeCSharp("LMSGetErrorString: " + errorCode);
return "";
}
setupScormApi();
</script>
<iframe id="frm1" src="./Content/index_lms.html" style="width: 100%; height: 100%"></iframe>
</body>
</html>
Exec solution by Mehonder
// story_content/user.js
let lastSlideLoaded = ''; //global variable
function Script1() {
if (lastSlideLoaded == '') {
lastSlideLoaded = 'X';
var ACT_firstID = window.globals.parsedParams["last_slide"]; //URL Argument
if (!ACT_firstID == (null || "" || "0")) {
Jump_Slide(ACT_firstID); //Set Slide
}
} else {
SetLastSlide();
}
}
function SetLastSlide() {
// send to last slide info to server//
var xhttp = new XMLHttpRequest();
var PACKID = window.globals.parsedParams["pack_id"];
var LASTID = window.DS.presentation.playerProps.attributes.CurrentSlideId;
var lastSlideURL = "/services_index.php?page=last_slide&pack_id=" + PACKID + "&last_slide=" + LASTID;
xhttp.open('GET', lastSlideURL, true);
xhttp.send();
}
function Jump_Slide(Target_Slide) {
// trigger slide change event //
g = DS.pubSub;
p = DS.events;
i = "_player." + Target_Slide;
g.trigger(p.request.NEXT_SLIDE, i, "_current")
}
This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle
I'm writing my first program to make an extension in Google chrome, i just took the "hello world" tutorial as example from here
This is my html file source code :
<!doctype html>
<html>
<head>
<title>Getting Started Extension's 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>
</body>
</html>
ad this is my javascript file source code :
var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=hello%20world&" +
"safe_search=1&" + // 1 is "safe"
"content_type=1&" + // 1 is "photos only"
"sort=relevance&" + // another good one is "interestingness-desc"
"per_page=20",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
var photos = req.responseXML.getElementsByTagName("photo");
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
for (var i = 0, photo; photo = photos[i]; i++) {
var img = document.createElement("image");
img.src = constructImageURL(photo);
document.body.appendChild(img);
}
}
// See: http://www.flickr.com/services/api/misc.urls.html
function constructImageURL(photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
The example is very simple and it works fine, but when add my own javascript instruction, it doesn't display it, the instruction that added is in showPhotos() function and it's :
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
in the result, i can see the other content but my 'h1' i don't see it.
i missed something ? can anyone help me please ?
Thanks
You're creating an element but you're not adding it to the page. So it can't be visible.
You can see it you add it, for example like this :
var element = document.createElement('h1');
element.appendChild(document.createTextNode ('tete '+document.location.href+'hgdfhgd'));
document.body.appendChild(element);
How do I add the ability to search xml tags by either first or last name using Javascript? At the moment it only works for first name. See code.
<html>
<head>
<script type="text/javascript">
function createRequestObject() {
var ro
var browser = navigator.appName
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP")
}else{
ro = new XMLHttpRequest()
}
return ro
}
var http = createRequestObject()
function sndReq() {
http.open('get', 'js2lab5.xml', true)
http.onreadystatechange = handleResponse
http.send(null)
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseXML.documentElement
listings=response.getElementsByTagName("LISTING")
for (i=0;i
if (nameobj[0].firstChild.data == document.getElementById("first").value){
addressobj = listings[i].getElementsByTagName("ADDRESS")
phoneobj = listings[i].getElementsByTagName("PHONE")
imgobj = listings[i].getElementsByTagName("IMAGE")
document.getElementById("address").innerHTML = addressobj[0].firstChild.data
document.getElementById("phone").innerHTML = phoneobj[0].firstChild.data
document.getElementById("photo").innerHTML = "<img src=' " + imgobj[0].firstChild.data + " ' />"
}
}
}
}
</script>
</head>
<body>
<form id="search">
<input type="text" id="first" />
<input type="button" value="Search Phonebook" onClick="sndReq()" />
</form>
<div id="address"></div>
<div id="phone"></div>
<div id="photo"></div>
</body>
</html>
And the XML code:
<?xml version="1.0"?>
<!DOCTYPE PHONEBOOK>
<PHONEBOOK>
<LISTING>
<FIRST>John</FIRST>
<LAST>Smith</LAST>
<PHONE>1-800-123-4567</PHONE>
<ADDRESS>320 E. John St, Champaign IL 61820</ADDRESS>
<IMAGE>smith.jpg</IMAGE>
</LISTING>
</PHONEBOOK>
Selecting nodes with XPATH is alot easier.
var query = nameobj[0].firstChild.data;
response.selectNodes("(//FIRST|//LAST)[text()='"+query+"']")
Sadly Microsoft and Firefox have a different model for selecting with Xpath so there's basically 2 solutions prototype selectNodes in FireFox as is shown here.
Or by including a great XML cross browser wrapper like Sarissa.
Depending on your needs the first might be good enough. If your planning on doing alot of stuff with XML in the browser investing in Sarissa will pay off tenfold.