This is my first time trying something out with eel. I've got a python script with some functions and I'm trying to communicate with them using #eel.expose but it gives me a javascript error - main.html:10 Uncaught TypeError: eel.startEncryption is not a function
Here's my code:
<head>
<title>Undefined</title>
<link rel="stylesheet" href="w3pro.css">
<script type="text/javascript" src="/eel.js"></script>
<script>
function startEncryption(mode){
massage = document.getElementById("massage").value;
code = document.getElementById("code").value;
string = eel.startEncryption(mode, massage, code);
document.getElementById("result").innerHTML += string;
}
</script>
</head>
<body>
<header class="w3-panel">
<h1>Vigenere Encryption</h1>
</header>
<div class="w3-panel">
<span>Message:<input type="text" id="massage"></span>
<br>
<span>Code:<input type="text" id="code"></span>
<br>
<span>Encrypted/Decrypted:<input type="text" id="result" readonly></span>
<br>
<input type="button" value="Encrypt" onclick="startEncryption(1)">
<input type="button" value="Decrypt" onclick="startEncryption(2)">
</div>
</body>
import eel
eel.init('C:\\Users\\Fantomas\\Documents\\Programming\\cipher\\web')
eel.start('main.html')
#eel.expose
def startEncryption(mode : int, message : string, code : string):
if mode == 1:
ciphertext = encryptMessage(code, message)
elif mode == 2:
ciphertext = decryptMessage(code, message)
return ciphertext;
I've got the eel.js file in my directory
Modufy the of your to:
import eel
eel.init('C:\\Users\\Fantomas\\Documents\\Programming\\cipher\\web')
#eel.expose
def startEncryption(mode : int, message : string, code : string):
if mode == 1:
ciphertext = encryptMessage(code, message)
elif mode == 2:
ciphertext = decryptMessage(code, message)
return ciphertext;
eel.start('main.html')
put eel.start('main.html') after exposing all shared functions.
Looking for your comments.
Good Luck
Obviously, Not placing eel.start at the end of your code often causes the problem, But eel.init's position has nothing to do with this particualar issue.
I just wanted to tell you that sometimes, The issue is not with your py code itself, But rather with the part where you import eel into your html code, Remember, the eel.js is always generated wherever your eel.init folder has been specified as, So when importing your eel.js in your html code, Make sure its in that particular folder
For example, If you have specified a folder web in your py code:
PYTHON:
eel.init('web')
Then When you import eel in html, It must be like the following
<script src="./eel.js"></script>
NOTE: Here, The .html file is also in the web folder, And so eel.js is imported from the same directory.
So yeah, This often happens(Atleast to me) Make sure you didnt make a mistake while importing eel.js in your html code.
Related
I am relatively new to JS but very familiar with protobuf. I'm currently designing a web page hosted from a Java HTTP server, and would like to implement protobuf communication between them.
My issue is on the browser side. After some research I found the protobuf.js git page and attempted to use this within my javascript. I ran into issues firstly getting the module over HTTP because
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.X.X/dist/protobuf.js"></script>
uses text/plaintext and fails to return. Adding a type=text/javascript just led to protobuf is not defined.
I then tried to take the project source into my web root, and directly use this:
<script type="text/javascript" src="./js/protobuf-js/src/index.js" ></script>
and:
import * as protobuf from "./js/protobuf-js/src/index.js";
This worked and the web server returned the file. Now, this is where my understanding reaches it's limits. From what I can tell from the README page on git, it distinctly says
"The library supports CommonJS and AMD loaders and also exports globally as protobuf."
If I look inside index.js I see the following:
var protobuf = module.exports = require("./index-light");
which throws a Module is not defined in ES module scope exception in browser.
Nowhere else online could I find working examples of the protobuf.js being used in commonJS as it states in the git, it all refers to Node.js which I don't want to use as i'm using Java for the webserver side of things.
Am i being really dumb and missing something obvious?
Thanks
There are example in https://github.com/protobufjs/protobuf.js.
a small example:
hello.proto
syntax = "proto3";
message Test{
string msg=1;
}
test.html
<html lang="en">
<head>
<script src="//cdn.rawgit.com/dcodeIO/protobuf.js/6.11.3/dist/protobuf.js"></script>
</head>
<body>
<script>
function test(){
protobuf.load("hello.proto", function(err, root) {
var TestMsg = root.lookup('Test');
var payload = {msg:'hello'};
var result = TestMsg.verify(payload);
if(result) throw Error(result);
var msg = TestMsg.create(payload);
var binMsg = TestMsg.encode(msg).finish(); // this is the binary protobuf message
// to handle blob data from server via websocket, you need handle like below
// event.data.arrayBuffer().then(buf =>{
// var msg = TestMsg.decode(new Uint8Array(buf));
// }
// deserialize
var msg2 = TestMsg.decode((binMsg));
console.log(msg2.toJSON());
alert(msg2.msg);
});
}
</script>
<input type="button" value="test" onclick="test()">
</body>
</html>
I'm trying to create a chrome extension, with the main code being in python but I'm struggling. I've succeeded in sending information from the user inputted from the HTML side to the python script, but not the other way around. Here's what I have so far (or the code that seems to be the problem):
Python:
#app.route('/get_data', methods = ['POST'])
def get_data():
taken = request.get_data()
taken2 = taken.decode()
print(taken2)
strength = int(taken2) #this works, I use this later in the code
my_variable = 5 #just for example
return jsonify(my_variable), 200
background.js (javascript)
function myAction(input) {
console.log("input value is : " + input.value);
newish = input.value
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xxhttp.open("POST", "http://127.0.0.1:5000/get_data");
xxhttp.send(newish);
//so sending newish here works, this shows up on my python console (strength becomes this)
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
<script src="background.js" type="text/javascript">
</script>
</head>
<body>
<h1>A Thing!</h1>
<div style="padding: 20px 20px 20px 20px;">
<h3>Hello,</h3>
<p>User input please? : </p>
<input id="name_textbox" />
<button id="ok_btn" type="button">OK</button>
</div>
</body>
</html> stuff
What I'm aiming for is for the my_variable to be accepted into the javascript file somehow, and then the html being able to access and display the contents of my_variable. I've tried looking around, but nowhere seems to have the exact thing I'm looking for (send python variable to separate html file for chrome extension). I'm at a bit of a loss, any help would be greatly appreciated, thanks!
Better way of doing it
Since you want to send the variable from python to html by reading the file, this is better than using the FS module in javascript.
example index.html code:
<body>
<h1>Hello, {first_header:}!</h1>
<p>{p2:}, {p1:}</p>
</body>
python code for the above:
newFileCode = open("index.html", "r").read().format(first_header='goodbye',
p1='World',
p2='Hello')
open("index.html", "w").write(newFileCode)
output in the HTML file:
<body>
<h1>Hello, goodbye!</h1>
<p>Hello, World</p>
</body>
read more about file handling in python here
PREVIOUS ANSWER
You can parse the data using JSON. Although, you'll need a new Node.js module fs https://nodejs.org/api/fs.html.
Once you've installed that module, you have to maintain two JSONs, one being a JS variable and the other being an external .json file.
Use this code to write in external JSON files in javascript:
fs = require('fs');
var name = 'fileName.json';
var m = {"example": "HELLO"}
fs.writeFileSync(name, JSON.stringify(m));
Use this code to read an external JSON file in javascript:
JSON.parse(fs.readFileSync(name).toString())
To get/read the data from the external JSON file in python use this code:
import json
# Opening JSON file
f = open('fileName.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
You can edit the file from javascript and can read it in python using a while loop
I'm practicing emailing and I wanted to know if it's possible to execute Javascript code when you send and email using smtplib and email libs, and when your message contain HTML code ?
It seem that nothing append.
HTML file :
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</div>
<p class='Test'>This is my first sentence</p>
<script type="text/javascript">
var list = document.querySelector('p.Test');
list.innerHTML = "I want to change it";
</script>
</body>
</html>
Python Code:
import smtplib
from email.message import EmailMessage
def ConnectServer(User, Pass, Host):
SMTPServer = smtplib.SMTP_SSL(Host)
SMTPServer.ehlo()
SMTPServer.login(User, Pass)
return SMTPServer
def SendMail(Server, src, dst, data):
msg = EmailMessage()
msg['From'] = src
msg['To'] = dst
msg['Subject'] = 'Test envoi python'
msg.add_alternative(data, 'html')
Server.send_message(msg, src, dst)
def main():
#Define email adresses
me = 'AN_EMAIL#MAIL.com'
me2 = 'AN_OTHER_EMAIL#mail.com'
Server = ConnectServer(me, 'PASS', 'smtp.gmail.com')
with open('HTML PATH HERE', 'r', encoding='utf8') as File:
data = File.read()
SendMail(Server, me, me2, data)
pass
if __name__ == '__main__':
main()
I hope it's clear.
As far as i know we cant , i also tried to do this, i wanted to include a search bar for the table content in mail.
"No. JavaScript won't work in mails. A cool way to implement this feature
would be to include an image that points to your server, where you generate
the weather report server side and render it as an image, and return it to
the client.
Note though that Gmail caches images and depending on when he does it that
might not be refreshed."
Source : https://www.quora.com/
I'm pretty new to coding, and I'm trying to complete Codecademy's Javascript course. I've learned a little bit about HTML/CSS and I'm almost done with JavaScript. I've researched people having similar problems, but those solutions typically involve JQuery, which I haven't learned.
Here is my HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
Here is the beginning of my JavaScript:
alert();
// Acquire character's name and check to make sure it's a string
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control.
May I have your last name, please?'");
var nameCheck = function(charName) {
while (typeof charName === "number") {
charName = prompt("NASA Receptionist: 'Surely, your name is not
a number... Please, may I have your last name?'");
}
};
nameCheck(charName);
NOTE: index.html is in the same folder as main.js
When I open the index.html, nothing happens, not even the opening alert(). Am I missing something?
You have error in your script as you cannot make javascript statements in multiple lines without using escaping slash .
I was getting this error :
SyntaxError: unterminated string literal
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control.
Here is the modified code :
alert();
// Acquire character's name and check to make sure it's a string
//The \r\n\ will format the string in prompt and make it appear in new line
var charName = prompt("NASA Receptionist: 'Welcome to Mission Control. \
\r\n\May I have your last name, please?'");
var nameCheck = function(charName) {
while (typeof charName === "number") {
charName = prompt("NASA Receptionist: 'Surely, your name is not \
\r\n\a number... Please, may I have your last name?'");
}
};
nameCheck(charName);
Check in browser source file whether main.js is loaded.
use alert("= loaded =") to check alert is called or not
If you are not even getting the syntax error, then I think you maybe referencing main.js incorrectly. Are you sure you have this in the same directory as index.html.
Also, each time I run it, the typeof method returns "string", no matter if I enter a number or not.
alert(typeof charName);
I have recently started working with JavaScript and Node and I'm having trouble working with the .ejs files.
I'm trying to implement a button in my page that gets a string inserted in a textarea and runs a function to evaluate if that string is a xml code (more precisely a Vast Tag, but that's not the point.)
So, I have something like this:
<div class="clear vastClass">
<h3> Vast Tag </h3>
<div class="vastClass" hidden>
<div>
<p>Please validate your code!</p>
<input type="button" id ="buttonVast" value="Validate">
</div>
<textarea id="vastTag" name="vastTag" class="form_creatives" value="">Insert you Vast Tag</textarea>
</div>
</div>
<script>
$("#buttonVast").click(function(){
// TODO
}
</script>
So here are a few questions:
I'm trying to use the node module xml2js to see check the text and I have read something online already (I don't know if they are right). e.g.:
The browser is running the .ejs file, so if I try to require('xml2js') it won't understand
I tried to use the browserify package, but I can't seen to make it work
I can only call a file.js using if that file is in my public assets folder. (indeed any file I try to access I get an 404 Page Not Found Exception)
So, my questions is if anyone have any tips on a method that works where I can either use the node module inside my script, OR If can define a function in a file.js and then call this function into the script, OR if anyone knows how browserify works and if it can be used to fix my problem.
To check if the string in a textarea is xml you can use a regex expression. This checks to see if the input starts with
Here's a working fiddle: http://fiddle.jshell.net/mikemjharris/j1nL8rz0/
The specific code to check for xml:
function checkXML () {
var textToCheck = $('textarea').val();
if( textToCheck.match(/\<\?xml /) ) {
alert('this is xml!');
} else {
alert('not xml');
}
}
Thanks for the reply #mikemjharris, but it doesnt really solve my problem.
After a couple more days searching, I've found out how to use browserify, so I'll answer it myself.
First, I had to create a .js file, let's say, main.js, where I declared and defined all the functions I wanted to use, e.g.
Main.js:
var xml2js = require('xml2js')
validateVast = function(vast){
var parser = xml2js.Parser()
parser.parseString(vast, function(err, result){
if(result && !err){
console.log(result)
}
else{
console.log(err.toString())
}
})
}
Then, in the terminal I used the command below to add a Bundle file to my public resources folder:
browserify folder/main.js -o public/js/xml2jsBundle
Then, in my html file, I added the line
<script src="js/xml2jsBundle.js"</script>
And then was able to call my function in the body of the html like:
<body>
<script src="js/xml2jsBundle.js"</script>
<input type="button" value="Validate" class="bt_Add" onClick="validate()">
<textarea id="vastTag" name="vastTag" class="form_creatives" value=""></textarea>
<script type="text/javascript">
function validate(){
var vast = $("#vastTag").val()
validateVast(vast)
}
</script>
</body>
Well, I guess this is it.
Thanks for your help, bye