Is there a way of calling the Electron's element in HTML - electron

I wanted to use electron's element in HTML file so that when the URL is hit, I can get the data from web page and user details of the webpage.
var uName= username.sync() returns me in main.js. How to make use of the username that I have got or how can I make use of uName?
Note: have tried IPC and it did not work out.
main.js:-
const username = require('username');
var uName=username.sync();
global.sendUName = function(uName){
return uName;
}
Can we use the same in index.html? I used the below code and it gave me require is undefined, later I fixed it using browserify.
<html>
<head>
<script> let {remote} = require('electron');
const hello = remote.getGlobal("sendUName")();
document.write(hello);
</head>
</html>

Related

how can I change value in index.html from main.js in electron?

at main.js I got user information with access_token from oauth.
now I want to change value at index.html with user name
here, how can I send user name to index.html?
I know event.sender.send but isn' it located at ipcMain.on a result of ipcRenderer.send?
I want to sent some value after I got access_token
thanks
Assuming that your index.html page is just the main page of your renderer process and isn't an external page that you're hosting in a <webview>, you can just send the value to the renderer and have it change whatever it needs to change in your index.html:
index.html:
<p id="myParagraph"></p>
<script> require("./renderer.js"); </script>
main.js:
const mainWindow = new BrowserWindow({...});
mainWindow.loadFile("./index.html");
// ... later we get the `accessToken`
mainWindow.webContents.send("got-access-token", accessToken);
renderer.js:
ipcRenderer.on("got-access-token", (event, accessToken) => {
document.getElementById("myParagraph").innerText = accessToken;
});

WKWebView - Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin

I trying to read my local JSON file on IOS WKWebview. However Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin.
I'm using UIWebview before and it's work fine. However when i change to WKWebview this error happen.
$.ajax({
type: 'GET',
url: 'json_app/country_state_json.json?callback=?',
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json)
{},
error: function(e) {}
});
Please assist.
Unfortunately, at this point WKWebView does not handle JavaScript asynchronously loading files using the "file://" protocol [1][2]. It works when the files are loaded from the DOM, just not using ajax or jQuery's .get (which is just abstracted ajax).
Here's a hack that I am simultaneously proud of and not proud of:
I have an app that needs to load a JSON object based on some dynamic information and then process it to display the web content. Originally, I was trying to have the JavaScript get the JSON file dynamically:
The old HTML:
<html>
<head>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
The old JSON:
{
"myData": true,
...
}
The old JavaScript:
$.get("data.json", function (data) {
// Process the data and generate the content
}, "json");
With this, I was encountering the same problem that you were. WKWebView would not load the data.json file.
My hack was to include the JSON content as another JavaScript object that is included in the DOM. The new JavaScript script simply assigns the JSON data as a string into a global variable. Note that this string needs to be a single line, as JavaScript doesn't support multiline strings. Then, this new script is dynamically inserted into the DOM when the WKWebView loads:
JavaScript Data file (replaces the JSON file):
var data = '{ "myData": true, ... }';
Swift:
let jsonInsertion = "var node = document.createElement('script');" +
"node.setAttribute('src', 'data.js');" +
"node.setAttribute('type', 'text/javascript');" +
"var head = document.getElementsByTagName('head')[0];" +
"head.insertBefore(node, head.childNodes[0]);"
webView?.evaluateJavaScript(jsonInsertion, completionHandler: { (_, error) in
print(error)
})
The resulting HTML:
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
Now, your JavaScript should be able to access the data as a global variable, and convert it using JSON.parse(data). You might need to add some synchronization code to ensure that your script runs after the data script is inserted by the app.
Again, this is a hack, but it's working for me. Hopefully it might be useful to you until Apple allows the "file://" protocol.
I bet that you need to provide a full url in the request instead of a relative one. How about using:
url: document.URL + "/json_app/country_state_json.json?callback=",
(I removed the trailing ? - that is not correct and results in a malformed URL)

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

How to detect if a link works?

I need to know if a link will open.
See Maximilian Hoffmann's answer for a more robust solution.
An approach like this is common - hijack the timeout to redirect to a different URL. Would this approach work for you?
<a id="applink" href="comgooglemaps://?q=Red+Lobster+Billings">Show map</a>
<script type="text/javascript">
var backup = "http://maps.google.com/?q=Red+Lobster+Billings";
function applink(fail){
return function() {
var clickedAt = +new Date;
setTimeout(function(){
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink").onclick = applink(backup);
</script>
The solution is adding an iframe with the URL scheme to your page. It silently fails if the app is not installed, so you need to check via a timer if opening the app worked or not.
// detect iOS
if (['iPhone', 'iPad'].indexOf(navigator.platform) > -1) {
// create iframe with an Apple URL scheme
var iframe = document.createElement('iframe');
iframe.src = 'twitter://';
// hide iframe visually
iframe.width = 0;
iframe.height = 0;
iframe.frameBorder = 0;
// get timestamp before trying to open the app
var beforeSwitch = Date.now();
// schedule check if app was opened
setTimeout(function() {
// if this is called after less than 30ms
if (Date.now() - beforeSwitch < 30) {
// do something as a fallback
}
});
// add iframe to trigger opening the app
document.body.appendChild(iframe);
// directly remove it again
iframe.parentNode.removeChild(iframe);
}
I wrote a post with a more detailed example that uses this approach to open the twitter app on iOS if installed.
There isn't a way for you to know if a link will work but there is for Safari with something called Smart App Banners
<!DOCTYPE html>
<html>
<head>
<meta name="Google Maps" content="app-id=585027354"/>
</head>
<body>
The content of the document......
</body>
</html>
What it basically does is checking if an app is installed. If it's not installed the user will be directed to the app store. If it's installed the user will be able to open the app from the website with the relevant data you'd be normally passing using the url scheme.
You could use if for Google Maps.
The down side of this is that it will only work on Safari but it's still better than nothing.

How to safe print an external HTML inside a page? iFrame?

I'm making an API Test Tool which makes requests to external urls.
Most of these external urls return a JSON, but sometimes a HTML can be return as well, in these cases I would like to show the rendered HTMl.
My first solution was to render the returned HTML inside an iFrame.
<script id="response-body-content" type="application/vnd.response-body">
<%= raw response_body.gsub("script", "xcriptx") %>
</script>
<iframe id="response-body-preview"></iframe>
<script>
$(function(){
var ifrm = document.getElementById("response-body-preview");
var ifrmDocument;
if(ifrm.contentWindow) {
ifrmDocument = ifrm.contentWindow.document
} else {
ifrmDocument = ifrm.contentDocument
}
ifrmDocument.open()
ifrmDocument.write($("#response-body-content").text().replace(/xcriptx/g, "script"));
ifrmDocument.close()
});
</script>
I had to replace script to *xscript* to prevent the external HTML to break the my script tag container #response-body-content then to print in the iFrame I have to replace it back.
Is there any other workaround to print/render (safe) external HTML inside a page?

Resources