I am working on a plugin to modify a URL and update a page. The goal is to get the parent URL, modify it and then offer up a link that the user can click to go to the new URL.
I am able to get the URL and display it, then modify the URL and display it. However, when I try to create a link using the ID, the link URL is to the index.html for the iframe, not the newURL id that I am referencing. I know I am overlooking something but I have been through a ton of HTML documentation and can't solve it. Any help would be greatly appreciated. Image of bad URL
Thanks,
Scott
<!DOCTYPE html>
<html>
<body>
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<script>
var myAssetsServer = "http://localhost:8080"
var startingURL = parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
</script>
</body>
</html>
The two main issues to address were
Update the href value of the link element (from comment not an issue in actual code), and
Percent encode the # character as %23 in the URL to send it and what follows to the server:
Hash marks in a URL that are part of identifying a a resource on the server must be percent encoded.
By contrast, fragment identifiers at the end of an URL, e.g.
htpp://www.example.com/page.html#element-id
are used by browsers to request a page from the server and, after rendering the response, scroll down the page to the element with the same id as the fragment identifier.
The first raw hash mark (not the last occurrence) in a link's 'href` string introduces a fragment identifier.
Neither the fragment identifier nor its preceding '#' character are sent to the server as part of a request: they terminate a URL without forming part of it.
See also
Related What are fragment URLs and why to use them?
The description of unsafe characters in section 2.2 of RFC1738
The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it.
Additional issues may need addressing, depending on how the server application is written - or whether the posted code is final:
the double slash // in the URL looks strange but could be by design.
Comma characters in a URL are meant to be encoded as %2C unless being used as separators in the query component. They may work anyway, due to there being no assigned meaning of commas placed before the beginning of the query component, and server code may or may not impose a requirement for their usage (check with the developer).
When running the snippet on Stack Overflow, a dummy page location had to be set (example.com), which then generated undefined in the query component of the generated href value.
Example code snippet with fixes for 1 and 2:
"use strict";
var myAssetsServer = "http://localhost:8080"
var startingURL = "http://www.example.com"; //parent.document.location.href;
var myCustomSort = "imageSupplierImageID,assetType,filename";
var endingURL = myAssetsServer + "/app/#/search//" + myCustomSort + "/?" + startingURL.split("?")[1];
//Fix 1: escape the '#' in the URL
endingURL = endingURL.replace('#', "%23");
document.getElementById("currentURL").innerHTML =
"The original URL of this page is:<br>" + startingURL;
document.getElementById("newURL").innerHTML = endingURL;
//Fix 2: change the URL in the link
var anchorElement = document.querySelector("a[href=newURL]");
anchorElement.href = endingURL;
//Prevent link action on Stack Overflow:
anchorElement.addEventListener("click", function (event) {
console.log("href= %s", this.href)
event.preventDefault();
});
<p id="currentURL"></p>
<p id="newURL"></p>
Click this link to update sort
<p style="border-left: medium solid #DDD; padding-left: 2rem;">
Link deactivated in code snippet - hover over or click to see href value.
Related
I've been using the following for inserting urls for digital ads
var clickTag = "http://www.example.com";
<a href="javascript:window.open(window.clickTag)">
The company I work for sets up tracking URLs that we have been manually putting into ads and sending to media partners. It was recently requested by some of them that I instead use this function in their guidelines instead, which is based on the latest iab guidelines:
function getParameterByName(name) {
var match = RegExp('[?&]' + name +
'=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var clickTag = getParameterByName('clickTag');
<a href="javascript:window.open(clickTag, ‘_blank’);">
I guess what I need help understanding is where the URL goes in this version that I was previously adding as the var clickTag in the first version?
Just got word from a media partner that we aren't supposed to be adding the links ourselves and instead using the script based on the iab guidelines and they add the link as part of the upload process. Problem solved.
So it's kind of a dumb question but I'm really wondering how I can make this :
user type www.mydomaine.com/something
page display : something
and it does with anything he type after the domain name
I've no idea how I could do that. I know I can get an info from an URL with jQuery but how can i remove the thing like index.html in the url? My guess would be with the htaccess?
Also, there won't be any other page but this with some design, how can I make sure someone doesn't go anywhere else but on the page that display what he wrote after the domain name?
I hope that's clear, thanks for reading and your answers !
Pierre
When creating an anchor tag and adding an href (or making a URL) I needed the URL to have a protocol (http or https), so I made a validation to add it, and then you can access the parameters of the URL easier.
Also, if you want to remove the / from the pathname you can use a .replace('/', '') when using parser.pathname
For removing index.html from the URL, you can split the path and get only the first element, or the ones you need f.e. parser.pathname.split('/')[0]
var myUrl = "www.mydomaine.com/something"
if (!myUrl.startsWith('http')) myUrl = 'http://' + myUrl;
var parser = document.createElement('a');
parser.href = myUrl;
console.log(parser.pathname);
// Other option
var theUrl = new URL(myUrl);
console.log(theUrl.pathname);
I used this as a reference.
I have two pages on MyDomain.com. The index view which is visible from MyDomain.com/ and MyDomain.com/Foo/Bar. Each view has an ajax call to the other and each one pushes the state using the HTML5 History API.
There are the steps that create the problem:
Start at MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/ (Works as expected.)
Click the ajax link to MyDomain.com/ (Works as expected.)
Click the ajax link to MyDomain.com/Foo/Bar/
Now the URL appears as MyDomain.com/Foo/Foo/Bar/
I don't want a Foo Foo Bar.
My current workaround is to add "../../../" to the front of the URL, but this is inelegant and not foolproof. Another option is a regex expression to count the directory levels.
Is there a better way to get absolute URLs with the History API?
function push(updateElementID, controller, action, url)
{
if (typeof url == "undefined")
{
url = "/" + controller + "/" + action;
}
var state = {
id: updateElementID,
controller: controller,
action: action
}
history.pushState(state, null, url);
}
You may want to ensure that the base element of the href element in the DOM is cleared...at least in the following case, it works for me: On your shared layout page (_layout.cshtml), reset the absolute URL within the DOM by placing the following within the head tags:
<base id="htmldom" href="http://localhost:59805/"/>
of course replacing your port # and on launch, replacing the root URL to the actual domain name.
By doing this, you are setting, or resetting the href property and specifying a base URL for all other relative URLs.
Now would doing it this way would affect any user-input data preserved in the page between back and forward buttons? I'm guessing it would be fine, as the above only resets the href property, and any other info in the DOM should be there.
Essentially, I have this website, the content of which changes depending on what the user inputs into the query string.
When the user enters mysite.com/?1 it loads content for 1 and /?2 for 2
My problem is that I have a Facebook like button within my page, and to make it work I have written this js code:
<script type="text/javascript">
var sUrl = window.location;
document.getElementById('fbcom').setAttribute('href', sUrl);
</script>
this gets the url and allows the user to like different content from what is technically one file.
My problem is that when a user likes for example /?1 on facebook, if someone where to click this link on their newsfeed and decide that they like it too, technically they will be liking the page /?1-with all the additional facebook code on the end of the url, so heading back to /?1 the like has not registered.
How can I modify the above code to ignore any facebook rubbish on the end of the url when they are directed from facebook?
Important: the ID /?1 can be anything from a 1 digit to a 4 digit number e.g /?1234
My current JS ability is very poor. Thanks
You can combine the properties of location you actually want to keep -- which seems to be protocol, host, and pathname:
var sLoc = window.location;
var sUrl = sLoc.protocol + '//' + sLoc.host + sLoc.pathname;
You can also just use the pathname as relative-from-root:
var sUrl = window.location.pathname;
you can do that with regex:
var sUrl = window.location.toString().replace(/^(.*?)(\?.*)?$/, '$1');
I have a link in a texbox. When I click a button I want to take the title of the page of the link. How can do it with javascript or jQuery?
this post can give you a start
http://forum.jquery.com/topic/get-external-page-and-fetch-title-googled-a-lot-didn-t-find-any-solution
If the page is in the same domain, I'd say use an ajax request and get the title from the returned DOM object.
If it's a different domain, I'd say set a hidden IFrame to the location and when it's loaded get the title using something like:
document.getElementById('MyIframe').document.title
It is almost always done by backend script/crawler. It fetches webpage for You on server-side and returns parsed data by AJAX
try something like this
Google
<span id="titleGoesHere"></span>
--
$(document).ready( function() {
$('#googleLink').click(function(){
$.get(this.prop('href'), function(data) {
var $temp = $('<div id="tempData" />');
$temp.append(data);
var title = $('title', $temp);
$('#titleGoesHere').html(title.val());
});
});
});
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. And because we are using client-side Javascript on the front end for web scraping, CORS errors can occur.
...
Staying firmly within our front end script, we can use cross-domain tools such as Any Origin, Whatever Origin, All Origins, crossorigin and probably a lot more. I have found that you often need to test a few of these to find the one that will work on the site you are trying to scrape.
From this post, I wrote this working and self-contained fiddle:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
const url = "https://www.facebook.com/"
$.getJSON('https://allorigins.me/get?url=' + encodeURIComponent(url) + '&callback=?', function(data){
const content = replaceAll(data.contents, "<script", "<meta");
$("#content").append(content);
const d = $("#content");
$('#title').text(d.find('title').text());
$('#description').text(d.find('meta[name=description]').attr("content") || "None");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" style="display: none;">
</div>
<h3 id="title">Waiting...</h3>
<br/>
<p id="description">Waiting...</p>
A few comments:
Use a cross-domain tool through https
Don't forget to encodeURIComponent your url
I replaced script tags with meta tags so that none of those are executed when appended to the DOM (replace function from this question)
To be used, parsed jQuery must be added to the dom (see this question)