IpcMain and IpcRenderer call main.js function from index.html - electron

I am new to electron
This is my package.json :
{
"name": "hello",
"version": "1.0.0",
"description": "hello app",
"main": "main.js",
"scripts":
{
"start": "electron ."
},
"keywords": [],
"author": "Rushikant Pawar",
"license": "ISC",
"devDependencies":
{
"electron": "2.0.2"
},
"build":
{
"asar": true
}
}
and this is my index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<!-- Insert this line above script imports -->
<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<!-- Insert this line after script imports -->
<script>if (window.module) module = window.module;</script>
<script type="text/javascript">
$(document).ready(function ()
{
window.alert('messageText');
$("#InputData").on("click", function ()
{
var value = $("#searchtext").val();
mainjsfunction(value);
});
});
</script>
</head>
<body>
<h1>Hello World!</h1>
<form>
<div class="form-group">
<label for="exampleFormControlInput1">Input Text</label>
<input type="text" class="form-control" id="searchtext" placeholder="rushikant pawar">
</div>
<button type="button" id="InputData" class="btn btn-primary mb-2">Confirm identity</button>
</form>
</body>
</html>
My window.alert is working... but my click function and mainjsfunction is not working... Any help will be appreciated. Thank you in advance.

If your "mainjsfunction" is located in your main process (eg main.js) you can/should use ipc to trigger your function.
For example, in your main.js file you could do:
const {ipcMain} = require('electron')
ipcMain.on('call-mainjsfunction', (event, arg) => {
console.log(arg) // prints "ping"
var res = mainjsfunction(arg);
event.sender.send('reply-mainjsfunction', res)
})
And in your index.html or client js code you would do:
const {ipcRenderer} = require('electron')
ipcRenderer.send('call-mainjsfunction', 'ping') //eg placed in your onclick
ipcRenderer.on('reply-mainjsfunction', (event, res) => {
console.log(res) // result back in client/renderer
})
Reference: https://github.com/electron/electron/blob/master/docs/api/ipc-main.md

Related

SwaggerUIBundle : Specify base url

I need to test a api where :
API Url
http://api.mydomain.loc:20109/v1/
API Definition URL
http://api.mydomain.loc:20109/v1/swagger/swagger.json
The API definition is :
{
"openapi": "3.0.1",
"info": {
"title": "***",
"description": "***",
"version": "v1"
},
"servers": [
{
"url": "/v1/path1/path2"
}
],
"/ressource1": {
"get": {
"responses": {
"200": {
"description": "Success"
}
}
}
},
...
}
I follow this part unpkg in the documentation to start a local Swagger UI. I create the file "swagger-ui.html" with this content :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerIU"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist#4.5.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist#4.5.0/swagger-ui-bundle.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'http://api.mydomain.loc:20109/v1/swagger/swagger.json',
dom_id: '#swagger-ui',
});
};
</script>
</body>
</html>
When I open the page, the API definition is correctly loaded and Swagger UI displayed. But when I try out the endpoint "ressource1", Swagger UI call "http://api.mydomain.loc:20109/v1/path1/path2/ressource1". In my case, I want to call "http://api.mydomain.loc:20109/v1/ressource1".
How override the base path in Swagger UI with unpkg?
Here's another solution that uses a plugin with rootInjects. The main idea is the same as in #vernou's answer - update the OpenAPI definition dynamically.
<!-- index.html -->
<script>
const UrlMutatorPlugin = (system) => ({
rootInjects: {
setServer: (server) => {
const jsonSpec = system.getState().toJSON().spec.json;
const servers = [{url: server}];
const newJsonSpec = Object.assign({}, jsonSpec, { servers });
return system.specActions.updateJsonSpec(newJsonSpec);
}
}
});
window.onload = function() {
const ui = SwaggerUIBundle({
url: "http://api.mydomain.loc:20109/v1/swagger/swagger.json",
...
// Add UrlMutatorPlugin to the plugins list
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
UrlMutatorPlugin
],
// This will set appropriate data when Swagger UI is ready
onComplete: () => {
window.ui.setServer("http://api.mydomain.loc:20109/v1")
}
});
window.ui = ui;
};
</script>
Swagger UI has the parameter spec :
spec : A JavaScript object describing the OpenAPI definition. When used, the url parameter will not be parsed. This is useful for testing manually-generated definitions without hosting them.
The solution is to load manually the api definition, edit the definition and pass the edited definition to Swagger UI.
Example for json OpenApi Specification :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerIU"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist#4.5.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist#4.5.0/swagger-ui-bundle.js" crossorigin></script>
<script>
const swaggerUrl = "http://api.mydomain.loc:20109/v1/swagger/swagger.json"
const apiUrl = "http://api.mydomain.loc:20109/v1/"
window.onload = () => {
let swaggerJson = fetch(swaggerUrl).then(r => r.json().then(j => {
j.servers[0].url = apiUrl;
window.ui = SwaggerUIBundle({
spec: j,
dom_id: '#swagger-ui',
});
}));
};
</script>
</body>
</html>
Example for yaml OpenApi Specification :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="SwaggerIU"
/>
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist#4.15.5/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist#4.15.5/swagger-ui-bundle.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-yaml/4.1.0/js-yaml.js" crossorigin></script>
<script>
const swaggerUrl = "http://api.mydomain.loc:20109/v1/swagger/swagger.yaml"
const apiUrl = "http://api.mydomain.loc:20109/v1/"
window.onload = () => {
let swaggerJson = fetch(swaggerUrl).then(r => r.text().then(t => {
let j = jsyaml.load(t);
j.servers[0].url = apiUrl;
window.ui = SwaggerUIBundle({
spec: j,
dom_id: '#swagger-ui',
});
}));
};
</script>
</body>
</html>
You can copy this code and just edit the value in swaggerUrl and apiUrl.

Problem with input type="file" in Mozilla web extension

I'm porting extension from Chrome to Firefox.
Have an html with
<input type="file" id="protocol-file"/>
After pressing an extension button I see my input. Then start to select local file from disk - I see window with file list on my disk, but extension windows dissapeared (only in Firefox, in Chrome it still remains visible).
I tried to add
document.getElementById('protocol-file').onchange = function() {
alert('protocol-file changed');
};
but it doesn't work - I don't see alert after file selected.
It seems that extension finishes working on selecting files in Firefox. In Chrome everything is Ok.
index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<script src="main.js"></script>
<body>
<div id="container">
<div class="file-input-block">
<span class="file-label">Файл:</span>
<input type="file" id="protocol-file"/>
</div>
</div>
</body>
</html>
main.js
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('protocol-file').onchange = function() {
alert('protocol-file changed');
};
});
manifest.json
{
"name": "Example",
"version": "0.1",
"description": "Mozilla ext example",
"manifest_version": 2,
"permissions": [
"activeTab",
"tabs",
"notifications",
"http://*/",
"https://*/"
],
"browser_action": {
"default_title": "Example file select",
"default_popup": "index.html"
},
"browser_specific_settings": {
"gecko": {
"id": "my#examle.com",
"strict_min_version": "49.0"
}
}
}

JSTree: Uncaught TypeError: $(...).jstree is not a function

I use this piece of code o=in my ASP.NET Core application:
<head>
<script src='https://code.jquery.com/jquery-latest.js'></script>
<script src='~/lib/bootstrap/dist/js/bootstrap.min.js'></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jstree/jstree.min.js"></script>
<link rel="stylesheet" href="~/lib/jstree/themes/default/style.min.css" type="text/css" />
</head>
<div id="container2">
<script>
$(function () {
$('#container2').jstree({
'core': {
'data': [
{
"text": "Root node", "children": [
{ "text": "Kind node 1" },
{ "text": "Kind node 2" },
{ "text": "Kind node 3" }
]
}
]
}
});
});
</script>
When I run the project in VS as IISExpress app it works.
But If I run it as an desktop app I receive the error
Uncaught TypeError: $(...).jstree is not a function
What is wrong in the code?

firefox extension with native messaging application not working

I have a native application developed in Java (compiled jar) , the extension basically sends message to the native application with the user input and get response back into a label on to the web page.
The extension is working fine with Chrome but I am not able to execute the same in Firefox 58.0.1(quantum 64 bit).
Error in the browser console.
can not convert null to object
below is the snippet code and the error screenshots.
{
"manifest_version":2,
"name":"Firefox Automation Extension",
"version":"1.0",
"description":"Automation Extensions",
"icons": {
"16": "icons/synergy.png"
},
"browser_action":{
"default_icon": {
"32" : "icons/synergy.png"
},
"default_title": "Native Messaging Application Testing",
"default_popup": "index.html"
},
"background":{
"scripts": ["background.js"]
},
"applications": {
"gecko": {
"id": "webdom#oracle.com",
"strict_min_version": "58.0"
}
},
"content_security_policy":"script-src 'self' 'unsafe-eval'; object-src 'self'",
"permissions": [
"nativeMessaging", "<all_urls>"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"jquery-1.12.2.min.js",
"contentScript.js"
]
}
]
}
/* background.js */
browser.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.info("Received %o from %o, frame", msg, sender.tab, sender.frameId);
// As it is registered in registy
var host_name="xxxxxxxxxxxxxxxxxxx";
// Open port (for communication).
var port = browser.runtime.connectNative(host_name);
// Send message to native application.
port.postMessage(msg);
// Listen for response...
port.onMessage.addListener(function (msg) {
// Send data to the content.
browser.tabs.query({ active: true, currentWindow: true }, function (tabs) {
browser.tabs.sendMessage(tabs[0].id, msg, function (response) { });
});
});
port.onDisconnect.addListener(function () {
console.info("Disconnected.");
});
});
/* contentScript.js */
document.addEventListener("send-message-event", function (data) {
var request = data.detail.data;
console.log("content script : ", request);
// Send message to the background script
browser.runtime.sendMessage(request, null);
});
/**
* Listens to the background script and dispatches 'get-message-event'
* to the client when the data is received.
*/
browser.runtime.onMessage.addListener(function (response, sender, sendResponse) {
console.log(response);
// Send response to the front page
var event = new CustomEvent("get-message-event", {
detail: {
data: response
},
bubbles: true,
cancelable: true
});
document.dispatchEvent(event);
});
/* Main.js (script called from a html page )*/
$(document).ready(function () {
var sendMessageBtn = $('#send-message-button');
var inputElem = $('#input-text');
var responseElem = $('#response');
/**
* Send message operation
*/
sendMessageBtn.click(function () {
var request = {};
request.message = inputElem.val();
var event = new CustomEvent("send-message-event", {
detail: {
data: request
},
bubbles: true,
cancelable: true
});
console.log("From Main : ",event.detail.data);
document.dispatchEvent(event);
});
/**
* Get message event listener
*/
document.addEventListener("get-message-event", function (data) {
var responseObject = data.detail.data;
responseElem.text(responseObject.message);
});
});
index.html page
<!DOCTYPE html>
<html>
<head>
<title>Native Messaging</title>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="page-header">
<h2>Native Messaging</h2>
</div>
<div class="form-group">
<label for="input-text">Input message:</label>
<input class="form-control" id='input-text' type='text' value="Test" />
</div>
<button type="button" class="btn btn-block btn-default" id='send-message-button'>Send Message</button>
<hr>
<div class="well well-lg" id='response'>Response from Native app...</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
<!-- jQuery and JS files -->
<script src="jquery-1.12.2.min.js"></script>
<script src="main.js"></script>
</body>
</html>
While clicking on the send Message button I am getting can not convert null to object error.
the code is working fine in Chrome and i am able to get response from the Native application in chrome extension
I think the problem is because you have not registered your native application in regedit in:
HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\NativeMessagingHosts
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mozilla\NativeMessagingHosts
I would put in permission :
"tabs",
"nativeMessaging",
"<all_urls>",
"webNavigation"
to work with your browser.

jQuery Autocomplete UI get source from asp page

How to get source to Jquery Autocomplete UI from classic asp page?
i found that default code. But i want to take my results from another asp page. How may i send with asp and get jQuery?
I need little help.
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
one solution is to response write the data directly to the output.
e.g. this is how your classic asp:
I have no way to run this code but it should look something like that...
<%
function getListOfTags()
{
try
{
var objRs = new ActiveXObject("ADODB.Recordset");
}
catch (e)
{
alert("ADODB namespace not found.");
exit(0);
}
strTagList = "";
strConn = "Provider=" +DP+
";Initial Catalog=" +DB+
";Data Source=" +DS+
";Integrated Security=SSPI;"
strComm = "SELECT ProductID,ProductName,UnitPrice "+
"FROM Products " +
"WHERE CategoryID = 7" // select Produce
objRs.open(strComm, strConn, adOpenForwardOnly, adLockReadOnly, adCmdText);
objRs.MoveFirst();
while (objRs.EOF != true)
{
strTagList += '"'+objRs("TagName")+'",'
objRs.MoveNext();
}
objRs.Close
objRs = null;
return (strTagList);
}
%>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
<%= getListOfTags() %>
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
You can use a remote data source for jQuery auto-complete.
Check this EXAMPLE on jQuery.com
$( "#birds" ).autocomplete({
source: "search.asp",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Here search.asp is a page that returns you the list of items in JSON format.

Resources