How to get URL of loaded script in javascript - javascript

On my site mysite.com I load scripts from anothersite.com. Is there a way for a script running on mysite.com to know that it was downloaded from anothersite.com?

I found this to the the solution:
function serverName() {
var server = "";
//IE and EDGE can't use the case-insensitive 'i' in this selector
var path = $('script[src*="loader.js"]').attr('src'); //Look for the script tag of this script and get the URL
var regex = RegExp('.*\/\/.*?\/'); // gets this: http://mysite/
var m = regex.exec(path);
if (m && m.length) {
server = m[0].replace(/\/$/, "");//trim trailing slash
}
return server;
}

<!doctype HTML>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js" id="know"></script>
</head>
<body>
Hello
<script>
const gebi=id=>document.getElementById(id)
console.log(gebi('know').src)
</script>
</body>
</html>
This would work

const domain = location.hostname;
See more about location.hostname
The hostname property sets or returns the hostname of a URL.

Related

Conditional redirection depending on Current URL. through html

(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123#example.com
(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname
(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.
I tried the following successfully :
<!doctype html>
<html>
<head>
<body>
<div>
<p id ="dd"></p>
</div>
<meta charset="UTF-8"/>
<script type="text/javascript">
var iid=document.getElementById("dd");
var getURL=window.location.href;
var theString = window.location.href;
var theWord = "fname";
var theWordExp = /fname/g;
if (theString.search(theWordExp) == -1) { window.location.href=
('www.example.com/error-page'); };
</script>
</body>
</head>
</html>
Explanation:
"I want to check Current URL Parameter whether it contains any data in fname"
The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?
basically it's almost the same as your approach using the location href to parse the params
"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)
Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method
const getQueryParam = (name) => {
if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
let fnameParam = getQueryParam("fname");
if (!fnameParam) {
window.location = "http://www.example.com/error-page";
};
<!doctype html>
<html>
<head>
<body>
<div>
<p id="dd"></p>
</div>
</body>
</head>
</html>

How to Transfer the values from One URL to another URL in html

Need some help below:
Page 1 URL: www.example.com?name=emily&email=example#gmail.com
My current code on www.example.com/index.html:
<html>
<head>
<meta http-equiv="Refresh" content="0;url=www.test.com">
</head>
</html>
How do I write a code to pass the value of "name" and "email" to another URL?
It will look something like below
Desired Page 2 URL: www.test.com?name=emily&email=example#gmail.com
Sorry guys, I'm quite new to html and Javascript, please help me to modify my code by adding the required code so I can just use it and run.
Thanks in advance!
You could do something like
function appendQueryParams(sourceUrl, destinationUrl) {
const url = new URL(sourceUrl);
return `${destinationUrl}${url.search}`;
}
const newUrl = appendQueryParams('https://www.example.com?name=emily&email=example#gmail.com', 'https://www.test.com');
<script>
function replaceOrigin(url,newOrigin){
var splittingChar=""
if(url.includes("/")){
url=url.split("/"); splittingChar="/"
}
else{
url=url.split("?"); splittingChar="?"
}
url=url[url.length-1] //ensures that url is ONLY the params
var newUrl=newOrigin+splittingChar+url //joins the params from previous url to new origin
return(newUrl)
}
//example usage
var url1="www.example.com?name=emily&email=example#gmail.com"
var myUrl=replaceOrigin(url1,"www.test.com") //you can replace anyhow you want
console.log(myUrl)
var x=document.createElement('meta')
x.httpEquiv="Refresh"
x.content=`0;${myUrl}`
document.body.appendChild(x)
//you would see something flash for a bit because something was logged on the console but then the url changed thanks to the meta tag..
</script>
You can use window.location.search to get the query string and parse it with `URLSarchParams
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString)
let name = urlParams.get('name') // get name
let email = urlParams.get('email') // get email
let newUrl = `www.test.com?name=${name}&email=${email}` // build new url
Update get meta tag value using post https://stackoverflow.com/a/7524621/14959189:
function getMeta(metaName) {
const metas = document.getElementsByTagName('meta');
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute('name') === metaName) {
return metas[i].getAttribute('content');
}
}
return '';
}
console.log(getMeta('myUrl'));
<html>
<head>
<meta name="myUrl" http-equiv="Refresh" content="www.test.com">
</head>
</html>

How to open a URL and estimate the word count using JavaScript?

<html>
<head>
<script type="text/javascript">
function open_urls() {
var url1="https://finance.yahoo.com/";
var newpage=window.open(url1);
alert(newpage.document.body.innerText.split(' ').length);
}
</script>
</head>
<body onload="javascript: open_urls()"></body>
</html>
The code above did not work, how to access DOM for a different URL?
I'd like to open an URL and show the word count of that URL.
You can't simply open another window and page and expect to have access to it. The web follows many security policies to prevent operations like this, such as the Same-Origin policy. Long-story short, you can't access URLs that don't fall under the same-origin as the page you're calling from. You couldn't therefore access Yahoo finance in your example (most likely).
If you were calling from the same origin, you could use an API like fetch to get just the text and do a word count there, or you could even load an iframe and query that: myIframe.contentWindow.document.body.innerHTML.
So knowing that you cannot do this from the browser, you could do it from a NodeJS application (perhaps also using fetch):
var fetch = require('node-fetch');
fetch('https://finance.yahoo.com/')
.then(function(res) {
return res.text();
}).then(function(body) {
console.log(body);
// perform word-count here
});
I understand that you were hoping to do this from the browser, but unfortunately you will not be able to do so for origins that you do not control.
You can try this out.
In you index.html (suppose) write this:
<html>
<head>
<title>Index Page</title>
</head>
<script type="text/javascript">
function poponload()
{
testwindow = window.open("new_window.html", "mywindow","location=1,status=1,scrollbars=1,width=600,height=600");
}// here new_window.html is file you want to open or you can write any url there
</script>
<body onload="javascript: poponload()">
<h1>Hello this can Work</h1>
</body>
</html>
And suppose your new_window.html is like this:
<html>
<head>
<script>
function get_text(el) {
ret = "";
var length = el.childNodes.length;
for(var i = 0; i < length; i++) {
var node = el.childNodes[i];
if(node.nodeType != 8) {
ret += node.nodeType != 1 ? node.nodeValue : get_text(node);
}
}
return ret;
}
function run_this(){
var words = get_text(document.getElementById('content'));
var count = words.split(' ').length;
alert(count);
}
</script>
</head>
<body onload='javascript: run_this()' id="content">
<h1>This is the new window</h1>
</body>
</html>

WebBrowser DocumentText cannot navigate javascript without giving full path

When I try to pass my Html into WebBrowser.DocumentText which include JS.
<script src="jquery\script.js"> </script>
It is same path with my executable. But when open in Winform, it is unable to find the 'script.js'..
But when you enter the full path of script, it is working.
StreamReader stringReader = new StreamReader(htmlFilename, Encoding.Default);
StringBuilder sb = new StringBuilder();
string temp;
while (!String.IsNullOrEmpty(temp = stringReader.ReadLine()))
{
sb.AppendLine(temp);
}
stringReader.Close();
return sb.ToString();
Eventually I read html into StringBuilder, and pass it to WebBrowser.DocumentText. Any other way to make it works without giving full path of the script?
You can give like this into your HTML document
<script type="text/javascript" src="../jquery\script.js"></script>
in HTML Page
<html>
<head>
<script type="text/javascript" src={Fullpath}></script>
</head>
<body>
</body>
</html>
in C#
string ScriptfullPath = Application.StartupPath.ToString()+"\\jquery\\script.js";;
string htmlContent;
using (StreamReader reader = new StreamReader(Application.StartupPath + \\JQuery\\sample.htm"))
{
htmlContent = reader.ReadToEnd();
}
htmlContent = htmlContent.Replace("{Fullpath}", ScriptfullPath);
Then your HTML document will use Script file with full path...

JS/HTML5 remove url params from url

i have an url like this
/users/?i=0&p=90
how can i remove in js the part from
? to 90
can any one show me some code?
EDIT
i mean doing this with window.location.href (so in browser url bar directly)
i tryed
function removeParamsFromBrowserURL(){
document.location.href = transform(document.location.href.split("?")[0]);
return document.location.href;
}
also i would like to not make redirect, so just clean the url from ? to end
function removeParamsFromBrowserURL(){
return window.location.href.replace(/\?.*/,'');
}
If you only want the /users/ portion:
var newLoc = location.href.replace( /\?.+$/, '' );
You could also split the string, and return the first portion:
var newLoc = location.href.split("?")[0];
Or you could match everything up to the question mark:
if ( matches = location.href.match( /^(.+)\?/ ) ) {
alert( matches[1] );
}
One way is leftside = whole.split('?')[0], assuming there's no ? in the desired left side
http://jsfiddle.net/wjG5U/1/
This will remove ?... from the url and automatically reload the browser to the stripped url (can't get it to work in JSFiddle) I have the code below in a file, and put some ?a=b content manually then clicked the button.
<html>
<head>
<script type="text/javascript">
function strip() {
whole=document.location.href;
leftside = whole.split('?')[0];
document.location.href=leftside;
}
</script>
</head>
<body>
<button onclick="strip()">Click</button>
</body>
</html>
If you only want the /users/ portion, then you could just substring it:
var url = users/?i=0&p=90;
var urlWithNoParams = url.substring(0, url.indexOf('?') - 1);
That extracts the string from index 0 to the character just before the '?' character.
I had problems with #page back and forth referrals sticking in the url no matter which url redirect I used. This solved everything.
I used the script like this:
<script type="text/javascript">
function strip() {
whole=document.location.href;
leftside = whole.split('#')[0];
document.location.href=leftside;
}
</script>
<a onclick="strip()" href="http://[mysite]/hent.asp" >Click here</a>

Categories

Resources