How to Update URL for Dynamic URLs - javascript

ShareThis does not seem to have a way to update URL which dynamically changes for html5 history-enabled or ajax-driven sites.
I tried this function to update it but URL remains original:
function initShareThis(){
var el = document.getElementById("lotShareThis");
var target = el.firstChild;
for (var i in stWidget.shareables) {
if (stWidget.shareables[i].element === target) {
stWidget.shareables[i].url = window.location.href;
break;
}
}
el.firstChild.onclick();
}
I also tried this but no any effect:
stWidget.addEntry({
"url": document.location.href,
"title":document.title
});
Any good advice whoever came across this situation?

If you want to try this using AddThis, you can change the title and url by updating the page's title and history like this:
var title = "New Title"
window.document.title = title;
window.history.pushState({path: href}, title, href);
And then you just have to call:
addthis.toolbox('[selector for AddThis buttons]');
This will force all the share buttons to update themselves and use the new title/url specified. If you're still struggling with ShareThis, give this a try.

stWidget.shareables[0].url = window.location.href;

Related

How to change rel of the anchor in the page when href contains specific keywords

I have an affiliate related blog which means that Google wants all of my affiliate links to be marked as sponsored links with rel = "sponsored".
Not all of the links on my website are affiliate links so I only would like to trigger the script below when a href on the page contains specific keywords.
Let's say I have 3 types of affiliate href links.
abc178.com/ref=xyz
qrs221.com/ref=xyz
xyz952.com/ref=xyz
I only want this sript to run when 'abc', 'qrs' and 'xyz' is found in a href
<script type='text/javascript'>
function myFunction() {
var x = document.getElementsByTagName("a");
var i;
for (i = 0; i < x.length; i++) {
if (location.hostname!=x[i].hostname){
x[i].rel = "sponsored";
x[i].target = "_blank";
x[i].title = "Click to open in new window";
}}}
mft=setTimeout("myFunction()",0);
function LoadEvent(func){
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
}
else{
window.onload = function()
{
if(oldonload)
{oldonload();}
func();}}}
LoadEvent(function(){
myFunction();
});
</script>
I'm no programmer, but I suppose this is possible?
window.addEventListener('load', function(){
// make sure dom elements are rendered before sc run
let keywords = ['abs', 'qrs', 'xyz'];
document.querySelectorAll('a').forEach(anchor=>{
// iterate all anchor tags in dom
let href = anchor.getAttribute('href');
let flag = false;
keywords.forEach(kw=>{
if(href.includes(kw)){
flag = true;
}
});
if(flag){
anchor.setAttribute('rel', 'sponsored');
anchor.setAttribute('target', '_blank');
// anchor.innerHTML = 'Click to open in new window';
}
});
});
I totally understand how confusing those url references are: href, link, rel, src, hostname, location, especially for frontend beginners. however, those are essential conventions to adopt to build more flexible and sophisticated application.
I would say a simple way to remember,
href always refer to a anchor tag.
src indicates image or script url.
window.location and window.hostname are the current page url.
if the script above, I am trying to iterate all anchor tags, check if any's href contains the keywords, if so, overwrite their rel to sponsored and target to _blank (if you want to change the content text, do not use title, use innerHTML) instead.
here are some useful resources:
a
innerHTML

Handling random number of links by using AJAX Jquery

I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>

Difficulty constructing Absolute URL

www.baxter.com source page, shows most of the href links starting with the word baxter, like this -
href="/baxter/corporate.page?">About Baxter<
So the way I can construct an absolute url from the above is by combining the base url, www.baxter.com and the relative url /baxter/corporate.page?giving me www.baxter.com/baxter/corporate.page? which results in 404, cause the actual url is www.baxter.com/corporate.page?
I know how to generally parse relative URLs in PHP but is there a way to sense and remove words from relative urls like these?
Also mouseover on About Baxter on www.baxter.com web page displays the correct url, www.baxter.com/corporate.page? at bottom left of the page - where is this coming from? can it be accessed?
Will deeply appreciate any help/pointers...
EDIT on Nov 7:
In main.js, they are removing /baxter:
var fixer = function() {
var init = function() {
var digitasFinder = /(proto)|(cms-)|(teamsite-)/
, baxterFinder = /(\/baxter\/)/
, $allAnchors = $("a")
, $allForms = $("form");
digitasFinder.test(location.host) || ($allAnchors.each(function() {
var $this = $(this)
, actualHref = $this.attr("href");
if (baxterFinder.test(actualHref)) {
var newHref = actualHref.replace(baxterFinder, "/");
$this.attr("href", newHref)
}
}
),
$allForms.each(function() {
var $this = $(this)
, actualAction = $this.attr("action");
if (baxterFinder.test(actualAction)) {
var newAction = actualAction.replace(baxterFinder, "/");
$this.attr("action", newAction)
}
}
))
}
;
return {
init: init
}
}
Looks like some JavaScript executed on page load is modifying the hrefs of the links.
You could try duplicating the effects of the JS code (ie. remove '/baxter' from the links), or for a more generic solution, you could use a headless browser to execute the JS code and then evaluate the resulting DOM. Look into the Mink project for a PHP-based solution.

Page refresh goes back to home page when using History.js in ie9 and below

I've built a site that uses the History.js plugin to navigate from page to page with AJAX and update the URL accordingly. All works well except in IE; when you refresh the page it essentially loads the content from the first page you came to, not the current pages content. In "decent" browsers it doesn't load the content from any page, it just loads the entire page for that URL, which is what I IE should do.
I'm thinking it doesn't understand what to do with the hash. If you visit http://www.crownacre.voyced.com/contact-us/ it works fine, but when you visit http://www.crownacre.voyced.com/#contact-us/ (with the hash) it doesn't.
I've attempted to redirect the page if it detects a # in the pathname, but there is no way of detecting this as window.location.pathname and History.getHash() returns the path without any hash.
Any suggestions? I've seen a few websites using this plugin that have the same problem, and similar issues on here, but no solution.
Thanks in advance!
I ran into the same problem in my rewrite of tarheelreader.org. I'm using History.js and it is working fine except for the refresh issue in IE8. This hack is working for me.
In my startup code that only runs on initial page load I do:
var url = window.location.href;
if (url.indexOf('#') > -1) {
// ie refresh hack
controller.stateChange();
}
where controller.stateChange() is the state change handler I use for all History changes.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
context = hist.data;
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
You can see all the code in main.js and controller.js at https://github.com/gbishop/TarHeelReaderTheme
Edit
Further exploration has lead to a case where History.js uses the initial URL instead of the root. This hack seems to handle that case.
function stateChange() {
// handle changes in the URL
var hist = History.getState(),
url = hist.url,
bar = window.location.href,
context = hist.data;
//console.log("State changed...", url, context);
if (url != bar && bar.indexOf('#') > -1) {
//console.log('bar = ', bar);
// I think we only get here in IE8
// hack for hash mode urls
var root = History.getRootUrl(),
hashIndex = bar.indexOf('#');
if (root != bar.slice(0, hashIndex)) {
// try to fix the url
url = root + bar.slice(hashIndex);
//console.log('new url =', url);
window.location.href = url;
}
}
renderUrl(url, context).then(function(title) {
document.title = title;
});
}
This worked for me:
<script>
var url = new String(document.location);
if (url.indexOf("#") > -1) {
alert("There is a Hash in the path");
}
</script>
Edit:
function LocationTest()
{
var loc = window.location;
alert(loc.href);
alert(loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
alert(loc.href == loc.protocol + "//" + loc.host + loc.pathname + loc.search + loc.hash);
}
Sample Source: window.location explained
Maybe a solution:
Can you please try the History.js unofficial version 1.8a2 of my fork from:
https://github.com/andreasbernhard/history.js
...and give feedback? Thank you very much!

How to replace old URL in javascript pop-up with new URL

I need help of getting this piece of code to work
1) I want to automatically start a media player when a pop-up is open, by changing is URL params, that the pop-up has
2) When the user clicks on on the link I want to replace the old URL with the one the new one clicked. Try using location.replace just ends up being a constant loop.
Not having much luck with the code can anyone help????
var vidlink = $('.link').attr('href');
var autoplay = $('.link:first').attr('href');
var myurl = window.location.href,
paramsStr = autoplay,
paramsObj = {};
var newUrl = $.param.querystring(myurl, paramsStr );
if(window.location.href != newUrl){
location.replace(newUrl);
}
$('.link').click(function(){
loadPlayer(vidlink);
});
Open Player
player another show <a href='?v=53&a=false' class='link'>Ep2</a>
try windowname.document.location = newURL (where windoname is the name of the pop-up)

Categories