Chrome Extension - Execute simple JavaScript from popup - javascript

I've created a simple page which uses a JavaScript file and the onClick method to display different div tags. I have a much more complex program which signs a user in using ajax, it works fine in a browser but not in the popup
The more I read, and I've read everything on the developers site that I can find the more confused I get. Chrome extensions do not allow inline JavaScript which is fine, but I'm still not sure how I can actually write JavaScript. I know it has something to do with event handlers, but even that is just me guessing.
Can anyone take this program and show me what I need to change to get it to work in a popup using "manifest_version": 2 and no hacks. How do Google expect people to use JavaScript? There really needs to be a hello world program showing how to do this.
HTML:
<!DOCTYPE HTML>
<html>
<head>
<title> Pop Up </title>
<script src = "test.js"></script>
<style type = "text/css">
#signout
{
display:none;
}
</style>
</head>
<body>
<!-- ///////////////////////////////////////////// -->
<!-- //////////////// Log In Screen ////////////// -->
<!-- ///////////////////////////////////////////// -->
<div id = "login">
<form method="post" action="">
Username:
<input type="text" name = "user" id = "user"><br>
Password:
<input type="text" name = "pass" id = "pass"><br>
<input type="button" value="submit" onClick="logInPHP()" />
</form>
</div>
<!-- ///////////////////////////////////////////// -->
<!-- //////////////// Sign Out Screen //////////// -->
<!-- ///////////////////////////////////////////// -->
<div id = "signout">
Your are Currently signed in.<br />
Sign Out
</div>
</body>
</html>
Javascript:
function logInPHP(){
document.getElementById("login").style.display = "none";
document.getElementById("signout").style.display = "inline";
}
function signOutPHP(){
document.getElementById("login").style.display = "inline";
document.getElementById("signout").style.display = "none";
}

You can't use onclick attributes directly in the HTML file. Remove them and wrap your JavaScript code into the document 'DOMContentLoaded' event listener.
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("login").addEventListener('click', function(){
document.getElementById("login").style.display = "none";
document.getElementById("signout").style.display = "inline";
});
document.getElementById("signout").addEventListener('click', function(){
document.getElementById("login").style.display = "inline";
document.getElementById("signout").style.display = "none";
});
});

Related

JavaScript ground work for creating a bubble game

I need help with Javascript fundamentals the issue I am having is with my start button when it clicks on it supposed to create a prompt that asks the user for the first name and have it stored within that variable you created. I have the doc ready function working okay however the button is not working properly.
Here is my code and thank you for helping me
<!-- Name: <Put name here> Date: <Put date here> Class: CSCI2447, Javascript Fundamentals Project X \-->
<!DOCTYPE html>
<html>
<head>
<title>POP-The- Bubble (CSCI2447)</title>
<!-- CSS styles: This is for me to worry about; not you. -->
<link href="css/game.css" rel="stylesheet" />
<link href="[https://fonts.googleapis.com/css2?family=Sunshiney&display=swap](https://fonts.googleapis.com/css2?family=Sunshiney&display=swap)" rel="stylesheet">
<script src = "jquery-3.5.1.min.js"> </script>
<script> $( document ).ready(function() { var first Name = prompt("Enter First Name of Gamer:"); </script>
</head>
<body>
<div id="content">
<h1>Pop-The-Bubble</h1>
<p>After clicking "start", you will have 30 seconds to click
on as many bubbles as you can. The bubbles will appear quickley so be ready!
</p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start\_button">Start!</button>
</div>
<div id="gamespace">
<img class="gameimage" src="img/bubblefun2.png" height = "120" width = "120"
</div>
</body>
</html>
Your function should close with the closing curly braces } and bracket ) => })
$( document ).ready(function() { var firstName = prompt("Enter First Name of Gamer:") });
Also you have a space between first and Name, this will throw an error in javascript Unexpected identifier. Remove the space so it is one string as the variable name firstName

Uncaught TypeError running code to populate a form field on a different html page

I was trying to use the example from here:
https://developer.mozilla.org/en-US/docs/Web/API/Document/forms
for my own uses.
The above example is accessing a form on the same page. My example attempts to populate a field on a different page.
Here is the launcher html - launcher.html:
<!DOCTYPE HTML>
<html>
<head>
<title>Launcher page</title>
<script>
function launch(text) {
window.open("http://localhost/page2.html", '_blank');
let entryform = window.document.forms.newentry;
entryform.elements.town.placeholder = text;
window.focus();
}
</script>
</head>
<body>
<p>Click button to launch page2 and populate edit box on form</p>
<button type="button" id="launcher" onclick="launch('Edinburgh')">populate a text field on a different page</button>
</body>
</html>
And the launched page - page2.html:
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
<header>
<h1>This page launched from launcher.html</h1>
</header>
<main>
<form name="newentry">
<p>Town: </p><input type="text" name="town" value="">
</form>
</main>
</body>
</html>
But when I click the button on launcher.html I get an error on the launcher.html page:
entryform.elements.town.placeholder = text;
Uncaught TypeError: Cannot read property 'elements' of undefined
at launch (launcher.html:10)
at HTMLButtonElement.onclick (launcher.html:20)
Why is this elements property undefined?
How can I fix this?
EDIT
What I really wanted to do was simple, but the window.open object returned was not ready at the point I was attempting to edit. The really simple solution is like this:
function launch(text) {
let p2win = window.open('page2.html', '_blank');
p2win.onload = function(){
p2win.document.forms.newentry.town.value = text;
}
}
Your problem is that this code...
let entryform = window.document.forms.newentry;
is looking in the current window (ie launcher.html) for the form element. What you can do instead is save a reference to the popup window and access its elements via that reference.
let popup = window.open("http://localhost/page2.html", '_blank')
let entryform = popoup.document.forms.newentry
// and so on
As an alternative, I would consider passing a query parameter to the popup page instead of trying to manipulate it externally.
For example
window.open(`page2.html?placeholder=${encodeURIComponent(text)}`, '_blank')
and then in page2.html...
<main>
<form name="newentry">
<p>Town: </p><input type="text" name="town" value="">
</form>
</main>
<script>
let query = new URLSearchParams(location.search)
document.querySelector('form[name="newentry"] input[name="town"]')
.placeholder = query.get('placeholder')
</script>
Live demo ~ https://codesandbox.io/s/determined-archimedes-51vn2

JavaScript addEventListener on submit not working

it's a total newbie question, but I'm having serious issues with my first JavaScript task. I've decided to learn JS and start with a TODO List, and I'm now stuck at the very beginning.
The event listener that should trigger when the form is submitted doesn't work. When I change the event it listens for to "click", "focus" or "blur" it works, but not with submit. Can anyone be of advise?
PS. Is there a simple explanation for event.preventDefault(); ? What does it do, and when it should be used?
Thanks a million.
My HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form>
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<input id="submitNewTaskButton" type="submit" value="+">
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
My JavaScript:
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
newTaskInputForm.addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});
<input> elements don't raise submit events - it's the <form> that does that.
(in other words, you've attached the listener to the wrong element)
Two changes made here, the event listener add to the <form> not the input submit, also changed the <input> tag to <button> check this SO question to know the difference between them.
And for e.preventDefault(), basically its used to stop default HTML tags behavior, for example <a> tag when clicked they will redirect users to a different page or domain sometimes, also forms submit actions usually redirect the page too to a different page, e.preventDefault() will stop this behavior and let the developer decide what should happen after the form submit, or <a> anchor tag is clicked, when should it be used: this is up to the app design, so if the application you are working on require some HTML tags to behave differntly e.g <a> and <form> tags to do Ajax calls.
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
document.getElementById('newTaskForm').addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form id="newTaskForm">
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<button id="submitNewTaskButton" type="submit">+ form</button>
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
The submit event only exist on form element. Check here.
so, it is
<html>
...
<form id="form></form>
...
<script>
let form = document.getElementById('form')
form.addEventListener('submit',function(){})
</script>
</html>
The event.preventDefault() I think it is best explained here.
Welcome to Javascript.

Get Element Breaking Code

I'm trying to improve my Javascript by starting a simple web interface, but every time I try to add an event listener to an input field, it breaks my code.
Here's my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="colors.css">
<script src="spot.js"></script>
</head>
<div id="ask">
Search for an artist to see their top songs:
</div>
<form>
<input type="text" name="artist" id="artist-search">
</form>
<div id="sub">
submit
</div>
</html>
And here's my Javascript:
window.onload = loaded;
var inField;
function loaded() {
document.getElementById("sub").addEventListener("click", search);
inField = document.getElementById("artist-search");
}
//https://api.spotify.com/v1/search?q=tania%20bowra&type=artist
function search() {
alert();
//var query = "//https://api.spotify.com/v1/search?q=";
}
When I add the getElementById to "artist-search", the alert in the search function stops working. Why is this? And is there a better way to get the text in an input field when someone clicks a submit button using vanilla Javascript?

Creating a DOM element from a complicated HTML-string

Is it possible to create a DOM from an HTML string that includes link, style, script and comments?
In my app, the end user will be pasting some form code, for example:
<!-- Start comment -->
<link href="test.css" rel="stylesheet" type="text/css">
<style type="text/css">
#full_name{background:#fff; }
/* This is
another comment*/
</style>
<div>
<form action="process.php" method="post">
Full Name:<input type="text" name="full_name">
</form>
</div>
<script type='text/javascript' src='test.js'></script>
<!-- End comment -->
This is the jquery code:
$('#html-go').click(function (e) {
e.preventDefault();
var html_code = $('#html-code').val(),
obj = $('<div/>').html(html_code).contents();
alert(obj.attr("action"));
});
I want to load it into a DOM element for parsing but I get an undefined error. If the form code contains only that between the tags, then everything's OK.
Here's a JSFiddle that shows the error (paste the form code above).
You need to get your form inside your newly created div:
alert(obj.find('form').attr("action"))
See this JSFiddle.
$('#html-go').click(function (e)
{
e.preventDefault();
var html_code = $('#html-code').val();
console.log(html_code);
obj = $('<div/>').html(html_code).contents();
alert($(html_code).attr('action'));
});

Categories

Resources