How to inject js files into a html page when loading? - javascript

I'm a tester and I'm going to test a page index.htm. I'm not allowed to change the target.
To test the page, I need to change some production code to mock code. So I think what I can do is to inject my mock code in a separate js file into the page. The mock code in mock.js looks like as below:
ProductionFunc.prototype.load = function()
{ // return fake data object}
ProductionFunc.prototype.save = function()
{ // fake save }
As a result, the BODY of index.htm in the browser should contain one line like <script src="mock.js"></script>
So the problem is how can I inject my mock code into the page without modifying the physical disk file index.htm.
There are about 100 test cases so 100 different mock js files are created respectively. I also created a loader.htm with 100 buttons on it. When a button is clicked, a new index.htm (injected with one mock js) opens. I wonder if the file name can be parameterized or not.
I know it can be done by some server side technology, such as ASP.NET. But I wonder if it can be done with pure Javascript without having to start a server process.

Related

How to change content of a html file (like changing images) by clicking on a element of another html file

I am working on a project, and i want to know if there's any way to change content of a html file like images, text, etc. with javascript (without any framework) by clicking on elements of another html file.
In general the browser will prevent you from editing the content of any file on your hard drive, or any page served from another domain/base url. However, if both files are in the same project as shown below, you can make temporary edits to one file from the other;
/http
|-index.html
|-template.html
|-hello.png
index.html can contain a <script> tag with the following
// first we open a popup showing the other page
let window_template = open("template.html","_blank")
// now we can do whatever we want in the popup window from the original index.html:
let new_img = window_template.document.createElement("img")
new_img.src = "hello.png"
window_template.document.body.appendChild(new_img)
This does not (and cannot) save any changes to "template.html".
To actually make changes to files, you need to run your own server. Then index.html can send a request to the server, and the server will have the ability to make edits on behalf of your browser-based app. Check out Node.js and the Express server library... I found it approachable enough as server frameworks go.

Cordova updating part of page

I created a login page with javascript. After a succesful the function loadMainActivity is called. As of now the contents are as follows:
async function loadMainActivity(){
document.getElementById("container").innerHTML = "This is a text.";
}
It works. However, now I want to load a complete HTML page upon a succesful login. I tried several plugins to this end. However, all of them require me to load a file. As I see it I have two options:
Provide an extra file with the app. This would enable my users to see the source, which I don't want.
Host the file on a server. This would require my users to have an active internet connection when using the app, which I also don't want, for now at least.
I thought about "stringifying" the HTML page and replacing "This is a text." with the obtained HTML string. That way I could keep the source closed. But this seems like a lot of extra steps. Besides, I cannot find a good method to do this stringification of HTML text.
How to solve this problem for a Cordova app?
I found that this can be done with the jQuery library, nothing specific to Cordova:
async function loadMainActivity(){
$.get("mainactivity.html", function( my_var ) {
document.getElementById("container").innerHTML = my_var;
});
}

Django -- Generate URL for the webpage of a database object

I currently am working on a Django project that allows a user to upload a file (i.e. a .dat, .json, or .tar.gz), which then gets converted into the appropriate database objects with their various relations. The file can be uploaded either by using the interface on the web browser or via curl to the appropriate REST API endpoint. The site is currently a single-page sort of site that utilizes Bootstrap.js. The URL in the browser does not change whether the user is on the home page (which displays the most recent uploads) or clicks on one of the "blackboxes" uploaded ("blackbox" being the primary database object formed from the uploaded file). Clicking on a blackbox takes the user to a page of the list of "datapoints" that are inside the blackbox.
What I now need is for each blackbox page to have its own URL that can be returned in a response when a user or script uses curl to upload a blackbox. This is the pattern I was thinking of using in the URLconf:
r'^bb/(?P<bb_id>[0-9]+)/$'
where bb is short for "blackbox". How can I systematically make each blackbox page have its own URL following this pattern, when right now each blackbox page and the home page all have the same root URL (in development, localhost:8000)?
I have made some attempts (most likely very misguided) at something like this. One thing I tried was making a separate template for a blackbox page, using the extends template tag. The frontend Javascript has a function display_points that takes in a blackbox id and renders the list of datapoints, so I tried various hacky ways to call that function (which was in a file home.html) from within the blackbox page template, but nothing was successful. One thing that I hoped would work was using jQuery $.getScript for something like this:
$.getScript('blackboxes.js', function() { //blackboxes.js is the Javascript from home.html that I copied and pasted--hacky, I know
display_points({{ bb_id }});
})
but I keep getting 404 errors from trying to use $.getScript like this despite trying different paths for the Javascript file.
Also, just in case this is an important detail for this question, the front end utilizes Clusterize.js to help load the datapoints, since the blackboxes usually have at least several thousand datapoints.
One of the key things to making something like this work was the use of the right template tags in our home.html which we renamed to base.html to be more descriptive of what the template is for. urls.py was also modified so that two different URL patterns would map to the same base view in views.py; the two patterns were a "blank" pattern (i.e. r'^$') for the default home page and a pattern to view a particular blackbox (r'^blackbox/(?P<bb_id>[0-9]+)/$'). Different views would be rendered based on whether a bb_id (blackbox id) was in the URL pattern. If none, the default home view of the recent uploads would be rendered; otherwise, the datapoints of that particular bb_id would be rendered instead. In the base.html template, the if template tag was used to see if a bb_id existed; if so, the JavaScript function display_bb would be called, which takes in the bb_id to know which datapoints to display. Otherwise, the function display_10_recent_blackboxes would be called instead.
Another issue was sending a response that contained info that could be used to find and view the blackbox that was just uploaded. Originally, the main database insertion function insertBlackboxIntoDatabase would create the Blackbox model instance first and then fill it with datapoints created from the file uploaded. However, since the response is sent before that function is called, it was necessary to refactor the upload and insertion code such that the blackbox instance would be created first so that its ID could be part of the response. The ID would then be passed to the different upload functions (based on the filetype) that each end up calling insertBlackboxIntoDatabase, which now locates the Blackbox instance based on the ID passed to it and then proceeds to create and insert the datapoints.

Find out home path of web app using Javascript

I have a .NET MVC5 application using C#, HTML and Javascript.
I need to know the link of the host so I can send a specific file in a specific folder to the user.
In my local computer, when I test and develop the application, the path the app uses is the following:
localhost:1234/Home/Scripts/myScript.js
However, in the real deployment server, the path changes:
www.superhost.com/Apps/MyApp/Home/Scripts/myScript.js
I am trying to send this file to the user with the following JQuery, when a button is clicked:
$("a.btn.btn-default").click(function () {
download("/Scripts/myScript.js"); //download is a personal function, unimportant
return false; //prevent browser defualt behavior
});
The problem is that when I click the button, I get in the consolo an erorr - 404 error, which means the server is not finding the file.
In fact the server is searching for the file on the path "/Scripts/myScript.js", but the file is in "Apps/MyApp/Home/Scripts/myScript.js".
How do I make my javascript smart enough to figure the correct path?
One solution I use a lot is to inject a site-root URL into the page using something like this:
<body data-root="#Url.Content("~/")">
Which converts to the actual website base URL at runtime.
You then use that injected value, from all jQuery code, using:
var root = $('body').data("root");
You can simply prepend that to any relative URLs to make them work correctly:
$("a.btn.btn-default").click(function () {
download(root + "Scripts/myScript.js"); //download is a personal function, unimportant
return false; //prevent browser defualt behavior
});
Note: this approach will work in cases where the routing changes:
e.g / vs /home/index/ vs /home/ which are all the same page, but different URLs
Remove the leading / from your download path.
You actually don't need an absolute path (and to know server's home folder) to access a file, target it relatively from the page you invoke the download from.
note: If you are using page relative paths, you must make sure you don't move the page the download script is executed from.
I always use in my layout the next code:
<script type="text/javascript">
var rootUrl = "#Url.Content("~/")";
</script>
And when I need it, i use for example:
$("a.btn.btn-default").click(function () {
download(rootUrl + "Scripts/myScript.js"); //download is a personal function, unimportant
return false; //prevent browser defualt behavior
});

SocketStream not executing anything from a newly added JS file in client

I am doing this to load all JS files in app folder
ss.client.define('main', {
view: 'app.jade',
css: [
'libs/reset.css',
'app.styl'
],
code: [
'libs/jquery-2.1.0.min.js',
'libs/angular-1.2.10.min.js',
'libs/lodash-2.4.1.min.js',
'app'
],
tmpl: '*'
});
There are 3 files in app, 2 that came with the default project and 1 that I added. The first 2 work fine, but the one I added does not get executed!
The funny thing is that when there are errors in that file, I set them in the Chrome console, but no function gets executed or variable added to the page.
Any ideas why?
It will need access to the window variable/global-object.
Therefore you need to require it from your entry file. Typically this means having the lodash code file in your actual code (/client/code/[...]) directory. I.e. you wouldn't put it in your libs folder, but in your main app folder, although you can make another libs folder there.
This is what I've always had to do in order to require --for example-- bootstrapJS. It defies the organisation of the client side as they set it up, but it's the way things need to be done for stuff like this.
An alternative is to require it remotely (from CDN) from your main app.jade view file.
script(src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js")

Categories

Resources