How to detect hostname + basename with javascript - javascript

I am working on a project which I share with someonelse.
I have my host set up as http://dev.foobar which maps to a folder called foobar.com and I have no issues with my code, it all works as intended. However the other person has the same named folder foobar.com, but hasn't set up virtualhost, so he is using http://localhost/foobar.com
So, inside the code I have to send an ajax request to a URL http://dev.foobar/wp-admin/admin-ajax.php" however this won't work for the other guy, since his would be http://localhost/foobar.com/wp-admin/admin-ajax.phpso right now I am using this code to get the host and append the url wp-admin/admin-ajax.php
function get_host() {
if (window.location.hostname == "localhost") {
var host = "https://localhost/foobar.com/";
} else {
var host = "https://" + window.location.hostname
}
return host
}
And I am send request to ajax like this
var ajaxURL = get_host() + "/wp-admin/admin-ajax.php";
The problem with the function is that I am hard-coding foobar.com and I am not sure if there is another way to do this

Related

Unexpected URL generated while using window.location.hostname

I am trying to append URL, but it the generated URL is not as expected. Below is the code that I've tested and its outcome.
Since I'm using a local server to test my system, the desired request URL is http://127.0.0.1:8000/api/posts. I will be deploying this system to a remote server in the near future so I cannot use the request URL as it is now. Base on the code below, what I am trying to do is to get the current hostname and append it with the route URL but it produces weird URL. How to solve this?
Component
created() {
var test = window.location.hostname + '/api/posts';
this.axios.get(test).then(response => {
this.posts = response.data.data;
});
Route Api (api.php)
Route::get('/posts', 'PostController#index');
Just use an absolute URL in your axios requests if you don't want to have to configure a base URL:
this.$axios.get('/apiposts')
Where the prefixed / is the important part.
You probably do not need to set baseURL. Have you tried to define baseURL? For example:
axios.get(`${process.env.HOST}:${PORT}/api/categories`)
Add this code in your: /src/main.js
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}
See the solution here Set baseURL from .env in VueAxios
I think in your app baseURL is set to http://127.0.0.1:8000 (default) and you append the host to this url in this line var test = window.location.hostname + '/api/posts';. Try it without this.

How can I get the parent site, or the site where the file was sent from, in javascript?

I'm writing a node.js application with client-side javascript that uses fetch to get data from the node API that I wrote. I want to be able to put that application on any site (URL) without changing anything in the javascript. My current code goes something like fetch("http://localhost:8080/data.json"). If I wanted to deploy onto Heroku, for example, I would have to change that. Is there a way to overcome this fact?
Window location might do the trick, if I am understanding correctly. Set it into a variable like this:
For browser:
If the hostname is http://localhost:8000, using this:
// http://localhost:8000/data.json
var url = window.location.hostname + "/data.json";
fetch(url)
Heres another example.
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is
Page location is https://www.w3schools.com/js/js_window_location.asp
More info:
https://www.w3schools.com/js/js_window_location.asp
I see you wanted NodeJS, for server
var os = require("os");
var port = process.env.PORT || 8000
var url = os.hostname;
var final = url + ":" + port
// localhost:port
var hostname = os.hostname();

Secure .php file, called via JavaScript

Our clients use our free service using code like this:
<script type='text/javascript'>id='example'; width='640'; height='480';</script><script type='text/javascript' src='http://example.com/example.js'></script>
example.js looks like this:
if (typeof (width) == "undefined") {
var width = '100%';
}
if (typeof (height) == "undefined") {
var height = '100%';
}
if (typeof (p) == "undefined") {
var p = '0';
}
if (typeof (c) == "undefined") {
var c = '0';
}
if (typeof (stretching) == "undefined") {
var stretching = 'uniform';
}
document.write('<iframe allowfullscreen width="' + width + '" height="' + height + '" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="true" src="http://example.com/examplefile.php?id=' + id + '&p=' + p + '&c=' + c + '&stretching=' + stretching + '"></iframe>');
The problem is people are leeching examplefile.php. We tried using secure_link with nginx, and it worked great, but only for clients who are able to use PHP code in their sites, generating a random secure token with a key. Some other clients can only embed HTML code. Is there a way to secure the examplefile.php or maybe change the examplefile.php name randomly, and verify it against our server to stop the leeching?
Maybe using jQuery? We need to be able to make sure examplefile.php is begin called by this JavaScript code and not added manually as an iframe from external sites.
You could replace the JavaScript with a AJAX request that sends a custom HTTP Request Header with a token. Upon validating the token your server would respond with the URL for use in the iframe. This solution provides you with the opportunity to control the URL so you could randomise it.
An alternative is to send the request to a URL that indicates your intent to access the resource. It could respond with a session cookie which will be carried by the subsequent request for the iframe link.
Here's some vanilla JavaScript to get you started with the AJAX request.
var myURL = 'https://www.example.com/path/',
myCustomKey = 'Custom-Header',
myCustomValue = 'Custom-Token-Value',
myRequest = new XMLHttpRequest();
// open request so that custom header can be added
myRequest.open('GET', myURL, true);
// set custom header for request
myRequest.setRequestHeader(myCustomKey, myCustomValue);
myRequest.onload = function () {
// Request finished. Do processing here.
if (myRequest.status === 200) {
// Request was successful
// use the response
console.log(myRequest.response);
}
};
myRequest.send(null);
You will have to configure the server to support CORS. See https://enable-cors.org/server.html
If I understand correctly, you want to ensure you're the only one using this resource.
One way to do it is to replace example.js with a generated JS file example.php.
This file will have two responsibilities:
Verifying the request against your server
Output plain JS content, as if it were a JS file (with appropriate header data).
Update
This is my approach to be specific:
By using the example.php file (instead of the example.js), each time a user loads the file, initialize a unique session token for the client, in which you will validate immediately in examplefile.php. This way you can make sure (to some level) the request came from example.php

How to handle host name during Ajax call?

I am making an ajax call:
var hostUrl = location.hostname;
$.getJSON(hostUrl + "/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {
This is what I get in my network tab:
http://localhost:50020/localhost/DataMatrix/ItemTypeList/5001
Localhost gets appended on top of local host, however in production it works fine as url formed is (xyz: host placeholder).
xyz/DataMatrix/ItemTypeList/5001
Once I remove host url then it works great in local too, but fail in production:
$.getJSON("/DataMatrix/ItemTypeList/" + $("#filter > option:selected").attr("value"),
function (dataValue) {
How to handle such scenario during development so that I don't have to change the string when I am handing over the files to deployment team.
just remove the leading "/" ie:
$.getJSON("DataMatrix/ItemTypeList/" ...
This is because the the browser will automatically interpret the URL as being relative to the current host (e.g. "http://localhost:50020/" or "https://myhost.com/") and prepend that to your stated URL.
So if you put "DataMatrix/ItemTypeList" in your URL when deployed on "https://myhost.com", the ajax call will automatically make the call to "https://myhost.com/DataMatrix/ItemTypeList".

Rewriting a URL if it 404's

first timer here so be nice :3.
I am attempting to write a jQuery function that rewrites Amazon URL's to include affiliate tags, similar to what StackExchange does but with a twist.
The main differences is that I am attempting to the user to their closest Amazon Store - e.g. amazon.de - for german visitors. Due to Amazon's ASIN's differing in some countries I first want to check the new link, if it 404's I obviously don't want to direct my visitor there [1]
Here is my code that selects links to amazon.com, grabs the ASIN number and writes a shortlink to the product including the affiliate tag.
var tld_table = {'GB' : ".co.uk",'DE' : ".de",'CN' : ".cn",'AU' : ".ca",'IT' : ".it",'FR' : ".fr",'CA' : ".ca",'JP' : ".jp",};
var country = $.cookie("CountryCode");
//$.cookie by http://plugins.jquery.com/files/jquery.cookie.js.txt
var tld = tld_table[country] || '.com';
var regex = RegExp("http://www.amazon.com/([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})");
$('a[href*="amazon.com"]').each(function(){
var url = $(this).attr('href');
m = url.match(regex);
if (m) { //if ASIN found
var ASIN = m[4];
var shorturl = "http://www.amazon"+tld+"/dp/" + ASIN + "?tag="+ affTag[tld];
//http test for 404
//if 404 do not rewrite
//else $(this).attr('href',shorturl);
}
});
This works fine and will re-write the URL's but when I introduce ajax into the equation the script fails to rewrite any URL's.
EDIT
$('a[href*="amazon.com"]').each(function(){
var url = $(this).attr('href');
m = url.match(regex);
if (m) { //if ASIN found http://www.amazon.com/dp/B003DZ1Y8Q/?tag=derp
var ASIN = m[4];
var ajaxCall = $.get('ASIN.php?ASIN='+ASIN+'&tld='+tld+'&tag='+affTags[tld], function(data) {
var newlink = data;
console.log('New Link: '+newlink)
$(this).attr('href',newlink); //does not rewrite
})
ajaxCall.success(function() {
if(newlink != '404'){
$(this).attr('href',newlink);//does not rewrite
}
})
}
});
Above is the code I am attempting to use currently, ASIN.php builds & requests the new link, opens it using php's cURL and returns either a new link or '404'.
I think $(this) is failing to reference the link correctly, but I have no idea why.
The error says it all: is not allowed by Access-Control-Allow-Origin
It basically means that your javascript is not allowed to retrieve any URL outside of your domain. You can fix this by rewriting your ajax request to a local PHP script that checks the url.
It has something to do with http://en.wikipedia.org/wiki/Same_origin_policy
you can also use apache mod_proxy
ProxyPass /mirror/foo/ http://foo.com/
Then you can call the url /mirror/foo/ on your domain and it will pass the request to the forwarding remote url.
This is a common way of overcoming cross-domain browser restrictions.
http://httpd.apache.org/docs/1.3/mod/mod_proxy.html#proxypass

Categories