I'm working with a total of 3 files.
index.html:
...
subWindow
...
The fetch() function returns a callback in JSON format.
subWindows.js:
let micWindow
function subWindow(data) {
micWindow = new BrowserWindow({
width: 1280,
height: 800
})
console.log(data)
micWindow.show()
micWindow.loadFile('src/subWindow.html')
micWindow.webContents.on('did-finish-load', function() {
let javascript = `document.querySelector('body').innerHTML = '` + data + `'`
micWindow.webContents.executeJavaScript(javascript)
})
}
And finally subWindow.html which contains pure html. It also imports subWindows.js:
...
<!-- JS Imports -->
<script src="js/subWindows.js"></script>
...
Firstly, index.html console log prints JSON data for both onclick and subWindow() at MIC.js?[sm]:10. The subWindow.html shows [object Object] from executeJavascript, but the console is empty.
Secondly, doing the following doesn't work:
let javascript = `document.querySelector('body').innerHTML = '` + JSON.stringify(data) + `'`
or
let javascript = 'console.log(' + data + ')'
Both throw an exception Uncaught SyntaxError: Unexpected identifier in subWindow.html
JSON data isn't rendered by subWindows.js in subWindow.html but rather in index.html:
index.html imports <script src="js/subWindows.js"></script>
Why is it throwing an error?
How to pass JSON data from main to remote window as function parameter?
Preferably pass JSON to executeJavascript and inject it back into remote window's html.
Thanks for any feedback!
I'm not sure about the errors, but my solution is to put the data into the window by editing the HTML. Here is one way to do this:
// win is the window you are passing info to
var data = win.document.createElement('span');
data.innerHTML = json;
win.document.body.appendChild(data);
The program in the window would wait for the element to appear, and then use the value for the function.
Note:
I just noticed that your JavaScript doesn't have any semicolons at the end of the lines. You need to have one after every statement. :)
Related
I have an HTML page where several JavaScript, CSS and images files are referenced. These references are dynamically injected and user can manually copy the HTML page and the support files to another machine.
If some JS or CSS are missing, the browser complains in the console. For example:
Error GET file:///E:/SSC_Temp/html_005/temp/Support/jquery.js
I need somehow these errors reported back to me on the inline JavaScript of the HTML page so I can ask user to first verify that support files are copied correctly.
There's the window.onerror event which just inform me that there's a JS error on the page such as an Unexpected Syntax error, but this doesn't fire in the event of a 404 Not Found error. I want to check for this condition in case of any resource type, including CSS, JS, and images.
I do not like to use jQuery AJAX to verify that file physically exists - the I/O overhead is expensive for every page load.
The error report has to contain the name of the file missing so I can check if the file is core or optional.
Any Ideas?
To capture all error events on the page, you can use addEventListener with the useCapture argument set to true. The reason window.onerror will not do this is because it uses the bubble event phase, and the error events you want to capture do not bubble.
If you add the following script to your HTML before you load any external content, you should be able to capture all the error events, even when loading offline.
<script type="text/javascript">
window.addEventListener('error', function(e) {
console.log(e);
}, true);
</script>
You can access the element that caused the error through e.target. For example, if you want to know what file did not load on an img tag, you can use e.target.src to get the URL that failed to load.
NOTE: This technically will not detect the error code, it detects if the image failed to load, as it technically behaves the same regardless of the status code. Depending on your setup this would probably be enough, but for example if a 404 is returned with a valid image it will not trigger an error event.
you can use the onload and onerror attributes to detect the error
for example upon loading the following html it gives alert error1 and error2 you can call your own function e.g onerror(logError(this);) and record them in an Array and once the page is fully loaded post is with single Ajax call.
<html>
<head>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error1');" onload="alert('load');" type="text/javascript" ></script>
</head>
<body>
<script src="file:///SSC_Temp/html_005/temp/Support/jquery.js" onerror="alert('error2');" onload="alert('load');" type="text/javascript" ></script>
</body>
</html>
I've put together the code below in pure JavaScript, tested, and it works.
All the source code (html, css, and Javascript) + images and example font is here: on github.
The first code block is an object with methods for specific file extensions: html and css.
The second is explained below, but here is a short description.
It does the following:
the function check_file takes 2 arguments: a string path and a callback function.
gets the contents of given path
gets the file extension (ext) of the given path
calls the srcFrom [ext] object method that returns an array of relative paths that was referenced in the string context by src, href, etc.
makes a synchronous call to each of these paths in the paths array
halts on error, and returns the HTTP error message and the path that had a problem, so you can use it for other issues as well, like 403 (forbidden), etc.
For convenience, it resolves to relative path names and does not care about which protocol is used (http or https, either is fine).
It also cleans up the DOM after parsing the CSS.
var srcFrom = // object
{
html:function(str)
{
var prs = new DOMParser();
var obj = prs.parseFromString(str, 'text/html');
var rsl = [], nds;
['data', 'href', 'src'].forEach(function(atr)
{
nds = [].slice.call(obj.querySelectorAll('['+atr+']'));
nds.forEach(function(nde)
{ rsl[rsl.length] = nde.getAttribute(atr); });
});
return rsl;
},
css:function(str)
{
var css = document.createElement('style');
var rsl = [], nds, tmp;
css.id = 'cssTest';
css.innerHTML = str;
document.head.appendChild(css);
css = [].slice.call(document.styleSheets);
for (var idx in css)
{
if (css[idx].ownerNode.id == 'cssTest')
{
[].slice.call(css[idx].cssRules).forEach(function(ssn)
{
['src', 'backgroundImage'].forEach(function(pty)
{
if (ssn.style[pty].length > 0)
{
tmp = ssn.style[pty].slice(4, -1);
tmp = tmp.split(window.location.pathname).join('');
tmp = tmp.split(window.location.origin).join('');
tmp = ((tmp[0] == '/') ? tmp.substr(1) : tmp);
rsl[rsl.length] = tmp;
}
});
});
break;
}
}
css = document.getElementById('cssTest');
css.parentNode.removeChild(css);
return rsl;
}
};
And here is the function that gets the file contents and calls the above object method according to the file extension:
function check_file(url, cbf)
{
var xhr = new XMLHttpRequest();
var uri = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function()
{
var ext = url.split('.').pop();
var lst = srcFrom[ext](this.response);
var rsl = [null, null], nds;
var Break = {};
try
{
lst.forEach(function(tgt)
{
uri.open('GET', tgt, false);
uri.send(null);
if (uri.statusText != 'OK')
{
rsl = [uri.statusText, tgt];
throw Break;
}
});
}
catch(e){}
cbf(rsl[0], rsl[1]);
};
xhr.send(null);
}
To use it, simply call it like this:
var uri = 'htm/stuff.html'; // html example
check_file(uri, function(err, pth)
{
if (err)
{ document.write('Aw Snap! "'+pth+'" is missing !'); }
});
Please feel free to comment and edit as you wish, i did this is a hurry, so it may not be so pretty :)
#alexander-omara gave the solution.
You can even add it in many files but the window handler can/should be added once.
I use the singleton pattern to achieve this:
some_global_object = {
error: (function(){
var activate = false;
return function(enable){
if(!activate){
activate = true;
window.addEventListener('error', function(e){
// maybe extra code here...
// if(e.target.custom_property)
// ...
}, true);
}
return activate;
};
}());
Now, from any context call it as many times you want as the handler is attached only once:
some_global_object.error();
I have PHP script which acts as a DNode client. Then I have Node.js Dnode server which evaluates code which receives from PHP client and it returns DOM as HTML. However, Node.js acts strangely to me (beeing a Node.js newbie). It doesn't return anything, even though the returning string is not empty. My code is below:
PHP client code using DNode-PHP library:
<?php
require(__DIR__.'/../../vendor/autoload.php');
$loop = new React\EventLoop\StreamSelectLoop();
$dnode = new DNode\DNode($loop);
$dnode->connect(7070, function($remote, $connection) {
$js = 'var a = document.createElement("A");';
$js.= 'document.getElementsByTagName("body")[0].appendChild(a);'
$remote->zing($js, function($n) use ($connection) {
print_r($n);
$connection->end();
});
});
$loop->run();
?>
Node.js server code:
var dnode = require('dnode');
var jsdom = require("jsdom");
var server = dnode({
zing: function (n, cb) {
var document = jsdom.jsdom('<!DOCTYPE html>');
var window = jsdom.parentWindow;
eval(n);
var html = jsdom.serializeDocument(document);
// console.log(html);
cb(html);
}
});
server.listen(7070);
Console.log() clearly outputs <!DOCTYPE html><html><head></head><body><a></a></body></html> what is expected result. But it never gets to PHP client. But what is strange, if I change line cb(html); to cb('test');, PHP outputs "test". So the problem must be somewhere on the Node.js side. But I have no idea where to look for.
Thanks in advance for any hints.
How are you viewing the response? Through a web browser? If so, then you're depending on whatever you're evaluating in eval(n) to change the DOM of the document... If nothing changes, then you won't end up seeing anything because you'll have an empty DOM other than the html/head/body tags. It would be worth your time confirming that you're getting an empty response back and it's not just an empty DOM.
That being said, The eval function has any context of you wanting to execute it on the document/window you declare above. As it is, it is just executing in the context of node itself, not on the page you are attempting to create. To fix this, try using:
window.eval(n)
If you take a look at the example Creating a browser-like window object
on the Github page for jsdom, this will give you a better idea of how exactly to use this package.
https://github.com/tmpvar/jsdom
What you have above should look something like this:
var document = jsdom.jsdom("<!DOCUMENT html>");
var window = document.parentWindow;
window.eval(n);
var html = jsdom.serializeDocument(document);
cb(html);
Now you'll be executing the Javascript on the DOM you were previously creating :-)
Your problem is not in Node. When I use the server code you show in your question and try with this client code, I get the expected result:
var dnode = require("dnode");
var d = dnode();
d.on('remote', function (remote) {
var js = 'var a = document.createElement("A");' +
'document.getElementsByTagName("body")[0].appendChild(a);';
remote.zing(js, function (s) {
console.log(s);
});
});
d.connect('localhost', '7070');
I don't do PHP so I don't know what the problem might be on that side.
I'm having trouble while trying to load the following javascript object from a file with NodeJS:
{
queries:{
user:"SELECT * FROM users WHERE $1 = ?"
},
user:function(identifier){
return this.queries.user.replace('$1', "user_"+identifier);
}
}
With the require function:
var queries = require('./components/queries');
I get a parsing error on line 4, unexpected ',' right after the queries ending curly bracket.
I'm not sure what is wrong with this object since I can declare it in chrome console without any trouble, so I bet the issue is related with the way I include this piece of code in my main script. But I don't know how to include it properly.
Thanks for your help !
In commonJS you should use the exports object to set access to module variables.
exports.queries = {
queries:{
user:"SELECT * FROM users WHERE $1 = ?"
},
user:function(identifier){
return this.queries.user.replace('$1', "user_"+identifier);
}
}
And then add it like this:
var q_mod = require('./components/queries');
var queries = q_mod.queries;
//logs "SELECT * FROM users WHERE $1 = ?"
console.log(queries.queries.user);
You have 3 ways to do what you want:
Change the extension of the file to .json
Export the content as a node.js module:
module.exports = /* the object */
Read and parse it as a json file:
fs.readFile('path/to/file', function (content) {
var queries = JSON.parse(content.toString());
});
So I have this peice of code such as:
function image() {
var debug = true;
try{
var win = window.dialogArguments || opener || parent || top;
win.send_to_editor('[button size="" color="" link=""]place title here[/button]');
}catch(e){
console.log("Could not send to window: " + e);
}
}
That when Used will send some text from the popup window to my editor, my wysiwyg. How ever it keeps throwing the error:
Could not send to window: Error: Syntax error, unrecognised expression: [button size="" color="" link=""]place title here[/button]
this should just be sent to the editor, any ideas?
Try to change [ to < and ] to >. Or, if you do need square brackets, wrap it with some tags like span. e.g. <span>[button size="" color="" link=""]place title here[/button]</span>.
Since OP haven't shown the source of function send_to_editor, I can just guess that
win.send_to_editor will probably call something like jQuery('img',html), where html is the string he passed in. It should be a valid HTML fragment, because jQuery will parse it on the fly and return the elements in that context. Otherwise, it may cause parse error (e.g. Sizzle.error).
Update
As per OP's request, here is a simple example:
jQuery("img","<div id='whatever'><img url='a.png'/></div>").attr('url') will return string a.png. Here jQuery parses the second argument as a HTML fragment, retrieves the img part and eventually returns its url.
this is a continuation of my original question here link
You can see through my rather lengthy conversion with aaronfrost that we determined the jquery was loading in the .php (as seen on the network tab in CHROME) however it's trying to be ran as a script immediately. My question is where or not it's possible to load that in as plain text and simply then do a js parse out the needed data. Doesn't have to be jQuery this was just the route we were going in this example. I've also tried with the following code and recieve the exact same "Unexpected token" error. I think if there were a way to just some how handle the malformed JSON client side we would be able to make this work, in a ugly sort of way.
If javascript doesn't work do you think going the route of a java applet (preserve client cookies, non-server side) would achieve the desired end result i'm looking for?
<script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script type="application/javascript">
var url = 'http://www.makecashnow.mobi/jsonp_test.php';
//<!-[CDATA[
function JSONscriptRequest(fullUrl) {
// REST request path
this.fullUrl = fullUrl;
// Keep IE from caching requests
//this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
// Get the DOM location to put the script tag
this.headLoc = document.getElementsByTagName("head").item(0);
// Generate a unique script tag id
this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}
// Static script ID counter
JSONscriptRequest.scriptCounter = 1;
// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {
// Create the script tag
this.scriptObj = document.createElement("script");
// Add script object attributes
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("charset", "utf-8");
//this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("src", this.fullUrl);
this.scriptObj.setAttribute("id", this.scriptId);
}
// removeScriptTag method
//
JSONscriptRequest.prototype.removeScriptTag = function () {
// Destroy the script tag
this.headLoc.removeChild(this.scriptObj);
}
// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
// Create the script tag
this.headLoc.appendChild(this.scriptObj);
}
var obj = new JSONscriptRequest(url);
obj.buildScriptTag();
obj.addScriptTag();
//]]>
</script>