Performing JS methods on a URL submitted by the user? - javascript

I haven't found an answer to this, and since I'm pretty new to JS, I don't know if it's even possible.
I have a regular HTML form, where the only field is a user types in a URL (any URL) and clicks submit.
The URL will "be sent" to JS code that stores this URL in some variable, I guess. Basically, I need to be able to call getElementsByTagName() on any URL submitted by the user.
My point is to count up the number of times a URL contains a specified element, which I do know how to do :)
How do I interpret a URL submitted through a form by someone and then take that URL and be able to perform methods (such as getElementsById) on it? I want to return the count of the number of elements to the user.
Any ideas? Can this all be done in JS? Is this possible?

When you say "URL," I assume you are talking about the actual webpage and not the url string. In other words, you want to load the entire DOM into a javascript variable and then parse it with getElementsByTagName(), etc. Javascript cannot load this webpage due to the Same Origin Policy, unless users can only submit pages that are on the same domain as your site. If that was the case, you could use a frame. Otherwise, JS can't do it without Jsonp, which isn't going to work in this case.
However, all is not lost. You can have your JS make an asynchronous request (ajax) to your own server. Your server scripting language /can/ get the entire DOM of the webpage (e.g. PHP can do this with cURL). Then it can send the entire string back to JS as xml that can be parsed. Good luck.

You can't really do that from the client (the web browser) with nothing but Javascript, because security rules will prevent your page from fetching and examining content from a different domain. You'll need to send the URL to a server and have it do the work.

Related

How to remove javascript code injection from a URL on HubSpot?

One of our clients received a social engineering warning from google. There is nothing hosted on the client's site and all I can assume is that the code is embedded in the URL. How can I stop this and make sure that the URL is not being taken advantage of?
Code below -
http://blog.essentialtech.com[.]au/events/public/v1/track/c/*W42X1Kh4VlKV7W4NDyrQ4Jwqwc0/*W34SKKS4FTw8nW7PlP8S8lBlFP0/5/f18dQhb0SfHC9dsQ84N7cW9rzHyjJqVS9MQR2B872gW3hHhb35zh-NRVnQ9Qq8Z_8m8W328bd38Xl1YFW2Mk5st5mZ50NMH5sdmJ4m23N8_dF8cJVPWRW4c2Tyb6d_m0TVHG2xy2R1bM2W2N6lzq4cj1_jW2pzD7d2MTPSyVKng6q1Wg4bjW58jf-C34RCjxW2p2f452LHP4rW5x5KNk7-XB_5N4Qzp5DMBCsfW7pKMHF2K4XMjW8tzC3F8q-1tCN1KKm4vRFkK4W5G18Kh3y9KYQN3dgtM7YrDrqW5hfJ425v5Cb1W8x-WCY3tg8kZN6p6WGsDLwCnW5BLL855GJB9nW5lW2Zn30_g8xW5kXBFn6n161-W38SQwr2Yy7gbW8Knjr38f7c2WW5rTvwF42SsX8W5nLxq_8r0-2RW30v4M38wyznpN3Gyjm6BNxmYW3gfMK48j556ZN8q1-LpjGXPKN64V3lHJRhw9VcZLWR86l4pCW8yq-Kr3rJTdsN5d_Q0Zj8tbNW480YZF3psJYWW8l-5SS6S8BxvW2RLxLy7X8G2fW5SdKBQ8s1s46W32wFFH1NsfDKSqhY367YLr102?_ud=617a5272-4c86-4d80-987a-d62228fd4f5e
This could be referring to a situation where in your code you're directly outputting the value of a query parameter or URL part in your page itself.
HubSpot has some automatic protections to prevent that kind of code injection, but there's still some best practices you should follow regardless of what CMS platform you're using.
Never trust query parameters as having only valid data. Never directly output it on the page. You can use HubL filters such as |escape and |striptags to remove potentially harmful code in the event you do need to display the value in the page.
An example of a time you might do that might be for a search results page, where you show "Search results for :"

dynamically generate content for a page when clicking on product

everyone. I am making a website with t-shirts. I dynamically generate preview cards for products using a JSON file but I also need to generate content for an HTML file when clicking on the card. So, when I click on it, a new HTML page opens like product.html?product_id=id. I do not understand how to check for id or this part ?prodcut_id=id, and based on id it generates content for the page. Can anyone please link some guides or good solutions, I don't understand anything :(.
It sounds like you want the user's browser to ask the server to load a particular page based on the value of a variable called product_id.
The way a browser talks to a server is an HTTP Request, about which you can learn all the basics on javascipt.info and/or MDN.
The ?product_id=id is called the 'query' part of the URL, about which you can learn more on MDN and Wikipedia.
A request that gets a page with this kind of URL from the server is usually a GET request, which is simpler and requires less security than the more common and versatile POST request type.
You may notice some of the resources talking about AJAX requests (which are used to update part of the current page without reloading the whole thing), but you won't need to worry about this since you're just trying to have the browser navigate to a new page.
Your server needs to have some code to handle any such requests, basically saying:
"If anybody sends an HTTP GET request here, look at the value of the product_id variable and compare it to my available HTML files. If there's a match, send a response with the matching file, and if there's no match, send a page that says 'Error 404'."
That's the quick overview anyway. The resources will tell you much more about the details.
There are some solutions, how you can get the parameters from the url:
Get ID from URL with jQuery
It would also makes sense to understand what is a REST Api and how to build a own one, because i think you dont have a backend at the moment.
Here some refs:
https://www.conceptatech.com/blog/difference-front-end-back-end-development
https://www.tutorialspoint.com/nodejs/nodejs_restful_api.htm

pass data using value of div (security)

is it safe to send the data(text) of div to the server via ajax? or get the url of an <a> tag and use it?
ex.
<div id="get-value">Some Value</div>
<button id="send" data-url="process.php"></button>
javascipt
$('#send').click(function() {
$.ajax({
url: this.dataset.url,
dataType: 'json',
type: 'post',
data: {
value: $('#get-value').text(),
}
});
});
What if I edit the text in the div and the data-url of button in the developer tools and click the button after?
It is safe to do this.
When working with Javascript and AJAX, you are subject to this inherent problem: it can always be modified. The best way to minimize the issue is to make sure that no secure operations occur on the client, and instead let the Javascript do the display and submit.
In this case, you can leave it as it is. As long as you are sanitizing the user input on the server side then you are doing most all you can (aside from obfuscation, which is rarely a good idea in Javascript).
In my opinion, and I'm no security expert but this is how I deal with things, you should always validate and sanitise user input on the server side. If a user can submit data, they can tamper with it, so it is not safe until you have cleaned it up and made sure it is safe on the server.
I don't know what you are using for your server side, but most frameworks these days have built in ways of sanitising user input before committing it to, say, a database. I would look into the documentation of your server side language/framework to find out the best way to handle incoming user input safely.
is it safe to send the data(text) of div to the server via ajax? or get the url of an tag and use it?
Yes.
Note, however, that since it is coming from the browser, it is user input and should be treated as such. You can't assume that data you gave to the browser with the expectation that it would be sent back to the server isn't going to be tampered with.
Don't use such for things like authorisation. You can't trust the browser to tell you if the user is an admin or not. You need to have proper authentication and then do the authorization for the user on the server.
Don't use it without suitable escaping for the purpose. e.g. Don't stick it into SQL without using a bound argument. Don't stick it in HTML without converting special characters to entities (or using a HTML parser with a white list filter to clean out XSS risks).

Dynamic response with tracking pixels?

I am testing out some tracking pixel functionality in an ASP.Net 4 MVC architecture.
This article gives a nice way of setting a tracking pixel (image) that you can use to read a visitor's environment parameters and do some logging on the server side before completing the response.
What I would like to do is inject some Javascript, based on the account ID that the pixel came from. In the example above, the ID would be set by setting some query string parameters.
By the looks of that code, it can only be used to log data, as the response type is of type image.
Is it possible to accomplish this using the method shown above? If not, can I get some recommendations/sources on how to accomplish this using Javascript and tying this back into my .Net architecture where based on some logic, I can add some additional Javascript to the response?
If I have no other choice to go the JS route, I'm guessing it would be something along the lines of the Google Analytics tracking script that includes some parameters sent back through JS.
Thanks.
If the client is requesting an image and expecting an image, then that is what you need to return. Look at this type of HTML that would generate an image request:
<img src="test.jpg">
Clearing the client is expecting image bits to come back and anything besides that is going to mess up the display of that image.
If you want to put server-supplied javascript into the page, then simply have the client request some javascript like this:
<script src="test.js"></script>
Your server can then do it's logging upon that request and return whatever javascript it wants to from that request. If you want to return different javascript for every request, then you will need to defeat caching in the browser (there are a number of was to do that) so that the javascript is always requested from the server.
In general, I'm guessing that you don't need to return different javascript for every request. But rather, you can put a common block of javascript in the client page and that javascript can examine the environment and branch based upon what it finds. That's how Google Analytics works. One common piece of javascript is served to the client, that code examines the environment and then makes an ajax request with different parameters set that causes the right information to be recorded on the server.

Accessing URL executes JavaScript

I've coded an HTML page using jQuery for loading content. Now if I want to link directly to a submenu, is this possible to do with JavaScript?
So for example if someone goes to www.mydomain.com/submenu1/
then some JavaScript code will execute and load the needed contents?
Thanks a lot :)
Is it possible to realize that with htaccess?
You will more likely want to have a URL structure that only needs a page to load from the server once, then the server is only queried by JavaScript XMLHttpRequests. Loading content based on a "hard" URL would be pointless, since you're doing a server request anyways and might as well return the content in the response.
For keeping addresses unique while still keeping the "hard" URL the same (preventing multiple server requests), you can use the hash/anchor part of the URL. This means your address might look something like this: http://www.example.com/#/submenu1/
The #/submenu1/ part stays on the client, so only / on www.example.com is requested. Then it's up to your JavaScript to load the content relevant to /submenu1/. See a page of mine for an example of this: http://blixt.org/js#project/hash?view=code
Also have a look at this question: Keeping history of hash/anchor changes in JavaScript

Categories