I am using Laravel as my back-end and Angularjs as my front-end for my website. I need to pull some js code (advertisement purposes, like Adsense) from server side and run it in Angularjs.
I got some ideas from https://www.ng-book.com/p/Security/ . First I use $sce to make the js code trusted so that angularjs can run it,
$scope.safeJsCode = $sce.trustAsJs($scope.unsafeJsCode);
then I use ng-load to eval() the safeJsCode
<script ng-load="run()"> </script>
$scode.run() = function()
{
eval($scope.safeJsCode.toString());
};
However, I was not able to run it. Can someone give me some ideas on how to solve this predicament? Thanks!
So if I understand correctly, you think that ng-load can call your 'run' function.
Empty script tag won't fire a 'load' event, so no wonder that it is not being executed.
If you really need to dynamically load some script and execute it you don't need no script tags-just as soon as you fetch script from the server and get safeJsCode, eval it.
Now I don't expect you to heed my advice, but instead of doing eval(), you should really think about a way how you can achieve with just data. In most cases this can be solved by just having your own smart code.
There are case which comes to mind- like a dashboard with customizable widgets, where people can write 3rd party widgets. Problem is, these never catch on and they are very prone to bugs and usually are sluggish.
If you trully need dynamicity though, you could try loading those script with https://github.com/systemjs/systemjs
Related
Good morning,
I would like to wait for a message (logged to my browser's console by a script I imported in my HTML tag) to be logged and then do an action in JavaScript.
For example, I'd like to wait for "ABCD:READY" to be printed in the console to use a function called finallyStart().
Is it possible ?
I thought I only needed to read the content of stdout to do this, but it looks like browsers don't call their console output stdout...
I also tried to find an answer in stackoverflow, but none of the posts I found were similar to the one I'm currently writing.
I'm a novice when it comes to JS in browsers (I've only used NodeJS for back-end), so thanks in advance for your help !
I faced the same problem and eventually came up with this hacky but working solution.
First create a dummy element in your html.
<div hidden id="start"></div>
Make an event for that element call a function in your js script.
document.getElementById("start").onclick = main;
Then trigger that event manually from your python script.
from pyscript import Element
Element("start").element.click()
No python code can execute until pyscript has finished initializing, so this seems like a reliable strategy. It would be even better if you could call the main() function directly from your python script, but i didn't have the patience to figure that out.
p.s. For some reason it takes a few seconds after pyscript has officially initialized for the code to kick off (at least in my test). I have no idea what's happening during that time, though i suppose it doesn't make a big difference to the already hefty build time.
I have an HTML file with some Javascript and css applied on.
I would like to duplicate that file, make like file1.html, file2.html, file3.html,...
All of that using Javascript, Jquery or something like that !
The idea is to create a different page (from that kind of template) that will be printed afterwards with different data in it (from a XML file).
I hope it is possible !
Feel free to ask more precision if you want !
Thank you all by advance
Note: I do not want to copy the content only but the entire file.
Edit: I Know I should use server-side language, I just don't have the option ):
There are a couple ways you could go about implementing something similar to what you are describing. Which implementation you should use would depend on exactly what your goals are.
First of all, I would recommend some sort of template system such as VueJS, AngularJS or React. However, given that you say you don't have the option of using a server side language, I suspect you won't have the option to implement one of these systems.
My next suggestion, would be to build your own 'templating system'. A simple implementation that may suit your needs could be something mirroring the following:
In your primary file (root file) which you want to route or copy the other files through to, you could use JS to include the correct HTML files. For example, you could have JS conditionally load a file depending on certain circumstances by putting something like the following after a conditional statement:
Note that while doing this could optimize your server's data usage (as it would only serve required files and not everything all the time), it would also probably increase loading times. Your site would need to wait for the additional HTTP request to come through and for whatever requested content to load & render on the client. While this sounds very slow it has the potential of not being that bad if you don't have too many discrete requests, and none of your code is unusually large or computationally expensive.
If using vanilla JS, the following snippet will illustrate the above:
In a script that comes loaded with your routing file:
function read(text) {
var xhr=new XMLHttpRequest;
xhr.open('GET',text);
xhr.onload=show;
xhr.send();
}
function show() {
var text = this.response;
document.body.innerHTML = text;//you can replace document.body with whatever element you want to wrap your imported HTML
}
read(path/to/file/on/server);
Note a couple of things about the above code. If you are testing on your computer (ie opening your html file on a browser, with a path like file://__) without a local server, you will get some sort of cross origin request error when trying to make an XML request. To bypass this error, either test your code on an actual server (not ideal constantly pushing code, I know) or, preferably, set up a local testing server. If this is something you would want to explore, its not that difficult to do, let me know and I'd be happy to walk you through the process.
Alternately, you could implement the above loading system with jQuery and the .load() function. http://api.jquery.com/load/
If none of the above solutions work for you, let me know more specifically what it is that you need, and I'll be happy to give a more useful/ relevant answer!
I'm just starting to use nodejs. I've done some basic learning course but I miss any basic example to start becaue I'm having problems to deploy an scenario for the first time.
The scenario I need to cover is:
I just need to write and read data from an Access.MDB file.
I have a basic example that works if I execute the js with the sentence \node appnodemdb.js from the command line.
But I need to execute it from another js in a web.
So I'd appreciate a lot if anyone could send me an example about execute it from an other js without the command line.
Thanks a lot for your help!
You can't call directly some NodeJS code with the browser. To achieve what you want, the simplest way to do is:
Create an HTTP server with a URL to will launch your write/write action and return some value (with Express for example).
This URL will be called by your JS in the browser (using XHR/Ajax) and process the data returned.
They are tons of alternative to do this, but since you tell us that you are beginner, I suggest this approach.
I've been trying to get this sorted all day, but really cant figure it out. I've got a page with <div id="ajax"></div> that is populated off a tab based menu pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
I've seen in places that I need to eval() the code, but then on the same side of things people say its the last thing to do.
Can someone point me in the right direction, and provide an example if possible as I am very new to jQuery / JavaScript.
Many thanks :)
pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
Avoid doing this. Writing <script> to innerHTML doesn't cause the script to get executed... though moving the element afterwards can cause it to get executed, at different times in different browsers.
So it's inconsistent in practice, and it doesn't really make any sense to include script anyway:
when you load the same snippet twice, you'd be running the same script twice, which might redefine some of the functions or variables bound to the page, which can leave you in extremely strange and hard-to-debug situations
non-async/defer scripts are expecting to run at parse time, and may include techniques which can't work when inserted into an existing document (in the case of document.write this typically destroys the whole page, a common symptom when trying to load third-party ad/tracking scripts).
Yes, jQuery tries to make some of this more consistent between browsers by extracting script elements and executing them. But no, it doesn't manage to fix all cases (and in principle can't). So don't ask it to. Keep your scripts static, and run any binding script code that needs to happen in the load callback.
If you fetch html via Ajax, and that html has a <script> tag in it, and you write that html into your document via something like $('#foo').append(html), then the JS should run immediately without any hassle whatsoever.
jquery automatically processes scripts received in an ajax request when adding the content to your page. If you are having a particular problem then post some code.
See this link
dataType: "html" - Returns HTML as
plain text; included script tags are
evaluated when inserted in the DOM.
When building webapps with MVC web framworks like Django, Kohana, Rails and the like, I put together the application without JS-driven components initially, and then add them afterwards as "improvements" to the UI.
This approach leads to non-intrusive JS, but I don't have a good "standard" way of how to go about organizing the JS work. Most of the JS I write in apps like these are 10-30 line JQuery snippets that hook into some very specific part of the UI.
So far I often end up inlining these things together with the part of the UI they manage. This makes me feel dirty, I'd like to keep the JS code as organized as the python / php / ruby code, I'd like for it to be testable and I'd like for it to be reusable.
What is the best way to go about organizing JS code in a setup like this, where we're not building a full-blown JS client app, and the main meat is still server side?
I am also very interested in what other people have to say about this. The approach I've taken is to use object literal notation to store the bulk of the function, and store these in one file included on all pages (the library)
uiHelper = {
inputDefault:function(defaulttext){
// function to swap default text into input elements
},
loadSubSection:function(url){
// loads new page using ajax instead of refreshing page
},
makeSortable:function(){
// apply jQuery UI sortable properties to list and remove non javascript controls
}
}
Then I include a .js file on any page that needs to use the library that ties the elements on that page to the function in the library. I've tried to make each function as reuseable as possible and sometimes the event binding function on the page calls several of my library functions.
$(document).ready(function(){
$('#mybutton').live('click',uiHelper.loadSubSection);
//more complicated helper
$('#myotherbutton').live('click',function(){
uiHelper.doThisThing;
uiHelper.andThisThing;
});
});
edit: using jsDoc http://jsdoc.sourceforge.net/ notation for commenting for these functions can produce documentation for the 'library' and helps keep your code easy to read (functions split by comments).
The following question is along similar lines to your own - you should check it out...
Commonly accepted best practices around code organization in JavaScript
When dealing with JS code, you should first analyze whether it will be used right away when the page loads. If it's not used right away (meaning the user must do something to invoke it) you should package this into a JS file and include it later so the load time is perceived faster for the user. This means that anything that the user will sees should go first and JS related to the functionality should be imported near the end of the file.
Download this tool to analyze your website: http://getfirebug.com/
If the JS code is small enough, it should just be inline with the HTML.
Hope that helps a bit.
For quick little user interface things like that I put everything into a single javascript file that I include on every page. Then in the javascript file I check what exists on the page and run code accordingly. I might have this in UIMagic.js for example. I have jQuery, so excuse those jQuery-isms if they aren't familiar to you.
function setupMenuHover() {
if ($("li.menu").length) { // The page has a menu
$("li.menu").hover(function() { ... }, function() { ... });
}
}
$(setupMenuHover);
function setupFacebookWizbang() {
if (typeof FB != "undefined") { // The page has Facebook's Javascript API
...
}
}
$(setupFacebookWizbang);
I've found this to be a sane enough approach.
My preferred method is to store inline javascript in it's own file (so that I can edit it easily with syntax highlighting etc.), and then include it on the page by loading the contents directly:
'<script type="text/javascript">'+open('~/js/page-inline.js').read()+'</script>'
This may not perform well though, unless your templating library can cache this sort of thing.
With Django you might be able to just include the js file:
<script type="text/javascript">
{% include "js/page-inline.js" %}
</script>
Not sure if that caches the output.
If you are still worried about being 'dirty', then you could check out the following projects, which try to bridge the server/client side language mismatch:
http://pyjs.org/ (Python generating JavaScript)
http://code.google.com/webtoolkit/ (Java generating JavaScript)
http://nodejs.org/ (JavaScript all the way!)