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);
Related
The result in the text file is always saving the file with a linebreak not just the p tag in div1 when clicking the button.
example:
<p>x1</p>
....linebreak
If I click the button 3 time and reload the page and click the button again I get this as well.
<p>x1</p><p>x2</p><p>x3</p>
<p>x1</p>
html code:
<button id="btn" value="" onclick="btn();return false"style="margin:1px"> Write to file </button>
<div id="div1" style="width:200px; border:1px; margin:5px 0px;"></div>
Javascript code:
// Read or Write to file
var path = 'c:\\home\\lab.txt';
var num = 0 ;
var myDiv = document.getElementById('div1');
// Read or Write to file
var path = 'c:\\home\\lab.txt';
var num = 0 ;
var myDiv = document.getElementById('div1');
myDiv.innerHTML = readFileInIE(path);
function readFileInIE(path) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 1);
var rfileContent = file.ReadAll();
file.Close();
return rfileContent;
} catch (err) {
alert('Unable to access local files or location. '+ err);
return "";
//}
}
function btn(){ //onClick Calls writeFileInIE and paragraph to file on new line.
num++;
var myInput= "P" + num.toString();
var myPara = '<p>' + myInput + '</p>';
myDiv.innerHTML = myDiv.innerHTML + MyPara;
writeFileInIE(path, myDiv.innerHTML);
}
function writeFileInIE(filePath, fileContent) { //Write to file function
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 2, true);
file.WriteLine(fileContent);
file.Close();
return fileContent;
} catch (err) {
alert('Unable to access local files or location.');
file.Close();
}
}
My goal is to be able to write to the file only the innerHTML from the div1 element innerHTML to the text only content in this format.
example in exact format I want even on a reload to the text file :
<p>x1</p>
<p>x2</p>
<p>x3</p>
<p>x1</p>
<p>x2</p>
Can't test your code but i see you comment and ending } , probably that is messing with your code.
//} after the return you should uncomment
function readFileInIE(path) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 1);
var rfileContent = file.ReadAll();
file.Close();
return rfileContent;
} catch (err) {
alert('Unable to access local files or location. '+ err);
return "";
//}
}
After that, try put a <br> maybe it will do that break you want
var myPara = '<p>' + myInput + '</p><br/>';
Ok many be with this you will see what I mean by not getting the correct format and it keeps adding a line break to the file c:\lab.txt. It works fine the with the button.
Until I reload the page or refresh it I get a newline Break so I end up with this
<p>P1</p>
<p>P2</p>
<p>P1</p>
<p>P1</p>
<p>P2</p>
<p>P3</p>
I want it to do this:
<p>P1</p>
<p>P2</p>
<p>P1</p>
<p>P3</p>
<p>P1</p>
<p>P2</p>
<p>P3</p>
I want it to allways save the file with out blank line breaks between the P tags.
It fine if I star with a blank document but once it reloads with data in the text file.
I will get a new linebreak saves in the middle.
Try to use the new code I have posted.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Page OPEN</title>
<Script language="JavaScript">//*/alert("helloWorld".toUpperCase())
</Script>
</head>
<body>
<h5> "Lab.txt file populating div1.innerHTML that is being changed via JavaScript while being save to Lab.txt"</h5>
<div id="div1" style="width:600px; height:150px; border:1px dotted; margin:5px 0px; overflow: scroll;"></div>
<table>
</tr>
<tr>
<td><button id="btn1" value="" onclick="btnWrite();return false"> Write to file </button></td>
<td><button id="btn2" value="" onclick="btnRead() ;return false"> Read from file</button></td>
</tr>
<tr>
<td>Content Sent to file</td>
<td>File Content</td>
</tr>
<tr><td><pre id="pre1" style='border:1px solid red ; width:300px; height: 300px; overflow: scroll;'></pre>1</td>
<td><pre id="pre2" style='border:1px solid blue; width:300px; height: 300px; overflow: scroll;'></pre>2</td>
</table>
<div id="lastDiv"></div>
<Script language="JavaScript">//*/alert("helloWorld".toUpperCase())
var lDiv = document.getElementById('lastDiv')
// Read or Write to file
var path = 'c:\\home\\lab.txt'; // Change to any location will create the file.
var num = 0 ;
var myDiv = document.getElementById('div1');
myDiv.innerHTML = readFileInIE(path);
function btnRead(){ //onClick Calls writeFileInIE and paragraph to file on new line.
document.getElementById('pre2').innerText = readFileInIE(path);
//document.getElementById("pre2").innerText = "hello";
}
function readFileInIE(readPath) {//Read file content
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(readPath, 1);
var readFileContent = file.ReadAll();
file.Close();
return readFileContent;
} catch (err) {
tkr("Error on reading: "+ path + " - " + err);//alert('Unable to access local files or location. '+ err);
return "";
}
}
function btnWrite(){ //onClick Calls writeFileInIE and paragraph to file on new line.
num++;
var myCode =""
var myInput= "P" + num.toString();
var myPara = '<p>' + myInput + '</p>'+'\n';
myDiv.innerHTML = myDiv.innerHTML + myPara;
document.getElementById('pre1').innerText = writeFileInIE(path, myDiv.innerHTML);
document.getElementById('pre2').innerText = readFileInIE(path);
}
function writeFileInIE(filePath, wFileContent) { //Write to file function
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var file = fso.OpenTextFile(filePath, 2, true);
file.WriteLine(wFileContent);
file.Close();
return wFileContent;
} catch (err) {
tkr("Error on write file: "+ path + " - "+ err);//alert('Unable to access local files or location.');
file.Close();
return err;
}
}
//*/
// track locations and find errors debug
function tkr(myData){lDiv.innerHTML = lDiv.innerHTML + "<p>" + myData + "</p>";}
tkr("JavaScript complete onload");
</Script>
</body>
</html>
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
In my JavaScript code I have the following line:
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed('test')'>Se resultat</button>");
The style and type properties work fine but when I try to pass a parameter to the JavaScript function Proceed it doesn't work. I have also tried (\'test\')
How do I solve this problem?
Edit: full html script
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title here.</title>
<script>
function Proceed(var test)
{
alert(test);
}
</script>
</head>
<body style="font-family:Palatino">
<img src="logo.png"/>
<hr/>
<h1 style="text-align:center">Description here.</h1>
<script>
if (window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("GET","data.xml",false);
var XMLdocument;
request.onreadystatechange=function()
{
if (request.readyState==4)
{
XMLdocument = request.responseXML;
}
};
request.send();
var questions = XMLdocument.getElementsByTagName("question");
for(i = 0; i < questions.length; i++)
{
var x = questions[i];
var questionvalue = x.getElementsByTagName("questionvalue");
document.write("<p style='margin-top:50px; font-size:20px; font-weight:bold; text-align:center'>" + questionvalue[0].childNodes[0].nodeValue + "</p>");
var answers = XMLdocument.getElementsByTagName("answer");
document.write("<form>");
for(n = 0; n < answers.length; n++)
{
y = answers[n];
var answervalue = y.getElementsByTagName("answervalue");
document.write("<input style='margin-left:43%; margin-right:20px;' type='radio' name='" + questionvalue[0].childNodes[0].nodeValue + "' value='" + answervalue[0].childNodes[0].nodeValue + "'>" + answervalue[0].childNodes[0].nodeValue + "<br/>");
}
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed(\"test\")'>Se resultat</button>");
}
</script>
</body>
</html>
It doesn't work because it's invalid HTML:
document.write("</form><button ... onclick='Proceed('test')'>...</button>");
Will be written as:
</form><button ... onclick='Proceed('test')'>...</button>
When it's written to the DOM, the quoting style of onclick dictates where it ends, essentially making the value of onclick Proceed(. You need to change your quoting characters:
document.write("</form><button ... onclick=\"Proceed('test')\">...</button>");
or:
document.write("</form><button ... onclick='Proceed(\"test\")'>...</button>");
Edit: See this plunkr for a simple example
Changing them to escaped double quotes should work for you.
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed(\"test\")'>Se resultat</button>");
You could change the single quotes to escaped double quotes:
onclick='Proceed(\"test\")'
Good day! I am trying to set a div's background image source with javascript and It doesn't seem to work. I get a weird error in the console from which I have no idea what to made of.
The code may seem a bit lengthy but I will try to make it as clear as possible:
The style basically contains 3 classes. 1 of them is the big box in which the picture and the text are stored. The others are just for the picture (with size) and the label (again with size).
The body contains a simple empty div element which will be dynamically field.
What is left is the javascript file: an array, the object from which the "news"'s different properties will be read (like title, views, image source)
and finally the only function which basically creates new div elements, gives them classes and appends them to the main one. The error is somewhere here.
The entire source code:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
.newsBox {
width:600px;
height:100px;
background-color:#B3CFDB;
float:left;
border-bottom: solid 1px;
border-bottom-color: #B9DDED;
}
.newsPic {
width:96px;
height:96px;
float:left;
margin-left: 4px;
margin-top:2px;
}
.newsLabel {
height:75px;
width: 500px;
background-color: white;
margin-top:20px;
float:left;
}
</style>
</head>
<body>
<div id="main" class="content"></div>
</body>
</html>
<script>
//create the object array and dummies
var arr = [];
var news = {
title: "",
views: 0,
srs: ""
};
var one = Object.create(news);
one.title = "Bender";
one.views = 132;
srs = "Bender.gif";
arr.push(one);
var two = Object.create(news);
two.title = "Salvation is upon us";
two.views = 777;
srs = "fryFuturama.jpg";
arr.push(two);
var three = Object.create(news);
three.title = "This website is a joke";
three.views = 0;
srs = "fry.jpg";
arr.push(three);
//Set up
var main = document.getElementById("main");
function loadNews() {
for (var i = 0; i < arr.length; i++) {
var p = document.createElement("DIV");
p.className = "newsBox";
main.appendChild(p);
var p1 = document.createElement("DIV");
p1.className = "newsPic";
p1.style.backgroundImage = "url(" + arr[i].srs + ")";
p.appendChild(p1);
var p2 = document.createElement("DIV");
p2.className = "newsLabel";
p2.innerHTML = arr[i].title + "</br></br>" + "Views: " + arr[i].views;
p.appendChild(p2);
}
}
loadNews();
</script>
EDIT: The error: Resource interpreted as Image but transferred with MIME type text/html: "file:///C:/Users/SameTime/Desktop/ObjectSetBackgroundImage.html"
A short answer to your big wall of code
change your
srs = "Bender.gif";
to
one.srs = "Bender.gif";
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
});