Get current object URL with JavaScript - javascript

I have a webpage uses object that are external websites (or other web pages).
for example:
<object data="external.html"></object>
on this page (external.html), the URL changes according to the navigation of the user. I want to know if there's a way to get the new URL using JavaScript/jQuery.
For example, when using:
<object data="www.google.com"></object>
If the user went from www.google.com to www.google.com/#q=JavaScript, I would like to get the second URL.
This won't work with Google, but theoretically speaking.
Alternatively, is there a way to display an external website and have access to the changing URL? Meaning, having a div populated by another website and somehow get the URL (after the user navigated through the site and the URL changes) with JavaScript/jQuery/some other way?
No need to manipulate this URL, just read access.

You can collect current URL using location.href and then collect object using its ID and then append data as current URL to it.

This should not possible as it will violate cross domain security policies. The same restriction is there with iframe, so I guess it applies to object as well.
If it is same domain, you can try getting the current URL from contentWindow or contentDocument
<objectElement>.contentWindow.location.href

Hope this is what you are looking for. You can split the url.
$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>

$('button').click(function() {
var urlSplit = 'www.google.com/#q=JavaScript'.split('/');
alert(urlSplit[urlSplit.length - 1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Click Me
</button>

Related

How to keep query string parameters as user navigates through the website

I have a situation where I want to preserve a query string between clicks on my Wordpress website.
E.g.
www.mywebsite.com/?utm_source=mysource
When navigating from this link to another page of the website that query string should persist.
E.g.
www.mywebsite.com/anotherpage/?utm_source=mysource
So I decided one easy way to do this would be to modify the javascript so that my function is fired when a click on an anchor tag occurs.
//Ensures that the query string persists between clicks on the site
$("a").on("click", function (event) {
event.preventDefault();
window.location.href = event.currentTarget.href + window.location.search;
});
However this doesn't work for other elements on the page like buttons which are not anchor tags but still contain hrefs that modifiy the window location when they are clicked. For example in the php scripts of the theme there is code such as:
<button onClick="location.href=www.anotherwebsite.com"</button>
I could implement another function that implements the same behavior for button elements but I am concerned that whenever another element is added I will have to check for a new type. Is there a better way to ensure that whenever the window location is changed my query string persists?
FYI: I am not allowed to put the information in a cookie which is another way I thought of keeping track of the parameters.
several suggestions
client side
In using jquery, it might be easier to just find clickable elements, or have the WordPress theme add css classes, if useful ones aren't there already.
server side
In WordPress, use sessions (but see below), and a rewrite or redirect rule using add_query_arg().
Note about sessions and WordPress: You can't rely on PHP sessions; instead use the database, perhaps via an existing plugin like WP Session Manager or WordPress Native PHP Sessions.
Try this to append query paramters in all anchor tags:-
$('a').each(function() {
var href = $(this).attr('href');
var querystring =
window.location.href.slice(window.location.href.indexOf('?') + 1);
if(href && querystring){
if(querystring.indexOf('=') >= 0)
{
$(this).attr('href', href+'?'+querystring);
}
}
});

How do I save article ids in Javascript or HTML?

I have a list of links in the web-page and users can click and comment on them. I load the links via JSON and each link is uniquely identified by an id.
My question is how do I know which link has been clicked? Even though I have an id, where do I store it(If Javascript object, how?)? I guess I cannot have it as a tag attribute because users may change it.
It sounds like you want to be able to create a link to a page with a specific ID, without actually displaying the ID? If this is the case, I think you'll face difficulties doing that in a simple way, as javascript client-side and the user will most likely be able to alter the id anyway. I'd recommend keeping the id in the link (<a href="url.com/post/42>, for example) and rather, when the page is loaded, in some way or another, check if the provided URL is actually a valid, existing ID.
You can use data attributes which stays hidden from end user.
Eg: <a id="link1" data-myuniqueid="XXXXX"> Link1 </a>
Using Javascript, you can access/modify data values
var ele = document.getElementById("link1");
var uid = ele.getAttribute('data-myuniqueid'); // For compatibility
var uid = ele.dataset.myuniqueid; // HTML5 way - does not work in old browsers
if you need more explaination for using custom data attributes, this might help.
-- EDIT --
I guess above answer will not be sufficient to address your problem. You can store objects in data attributes or try something like this -
var ele = document.getElementById("link1");
ele.myuniqueid = "XXXXXX"
myuniqueid will not be visible to user even in source.
You can add it as a tag attribute - anything that is send to the browsers, users can change. If a user wants to change the id - let him do it. He can also click on the article that he wants to comment on and do that as well.
You can use the sessionStorage in HTML5 suppoerted by all the browsers. It can also retain if the page gets reloaded
//for setting value
sessionStorage.LinkClicked= "4";
//to get the value
var temp = sessionStorage.LinkClicked;
Here is the link for more info http://www.w3schools.com/html/html5_webstorage.asp
Hope, it may help you. Have anice day. :)
for storing data on the client side.
if your not fussy about cross browser compadablility, you could go with a html5 soultion such as local storage.
http://html5sql.com/
http://diveintohtml5.info/storage.html
if your looking to get the id from a element and your using jQuery you can uses this in your event handler
$().attr('id');

Get Websites Title

I am trying to retrieve the title of a URL for a link.
For example get the title of this:
<a class="stack" href="http://stackoverflow.com" title="Stack Overflow">
will be generated dynamically from something like this: $('.stack').attr("title", "....");.
Is that possible with javascript or jQuery to retrieve the title of a URL?
Thanks alot
Took a little time to make, but this example allows you download a web page from your web page. Then extract the title from the title tags.
<html>
<head>
<!-- jQuery include -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- This include allows cross domain get requests -->
<script type="text/javascript" src="https://raw.github.com/jamespadolsey/jQuery-Plugins/master/cross-domain-ajax/jquery.xdomainajax.js"></script>
<!-- Sample -->
<script type="text/javascript">
$(document).ready(function(){
//gets the href of the first anchor
var url = $("a").first().attr("href");
//sets a get request to get the html source
$.get(url, function(data){
//uses get string between function to get the text between the title tags
//then calls it in a message box
alert(getStringBetween(data.responseText, "<title>", "</title>"));
});
});
function getStringBetween(input, start, end){
var index = input.indexOf(start);
if(index != -1){
index += start.length;
var endIndex = input.indexOf(end, index + 1);
if(endIndex != -1)
return input.substr(index, endIndex - index);
}
return false;
}
</script>
</head>
<body>
Google
</body>
</html>
Yep, just use document.title. Simple and effective.
$('.stack').attr("title", document.title);
EDIT: It looks like I misunderstood your question. If you want to get the title of another page, not the currently loaded page, you could do some cross-domain AJAX trickery, but it's not generally a good idea. I'd just grab the page title server side (in whatever you are using to generate the page [php, asp, etc]) and output it.
For security reasons, you cannot read content from a different website using Javascript, even just to read the title.
You could write a server-side proxy that requests a remote page and finds its <title> tag using an HTML parser.
However, you shouldn't do this at the client side; it will waste time and resources.
If you really want to do this, do it once on the server as a pre-processing step when you create a new page.
Unless the URL's href is on the domain of the current document, using JavaScript to try to get the title of the target document would require cross-domain scripting which is not generally allowed (using traditional methods) by browsers. Unless you're real fancy with proxies (not entirely sure how that is done), you'll need a server-side language to load the document first.

Open link to specific domain within an iFrame in a new window

I need to be able to open a link to a specific URL that is within an iFrame; the link is generated by php and I can't change the source code, so I need to change the link in the iFrame dynamically, if possible.
What I'm doing is this: on a non-profit organization's site, I have an affiliate store (generated by php) displayed within an iFrame on a page in order to make it more styled with the rest of the site. The php store pulls products from an affiliate service; the link to the store.php is in the same domain as the main non-profit's site.
The problem is the final "Buy Now" link from a product opens the final destination e-commerce store within the iFrame, and as such the page is stuck in the iFrame and looks bad and one must scroll V and H to see it and check out.
The link I need to open in a new window always has the class "av_buy_now" I have access to the CSS file, which I can change. I have access to the PHP files, i.e. shop.php, but it doesn't appear that the final link is generated locally. I'm showing the iframe this way:
<iframe src="http://nonprofit.org/shop/mj/shop.php"></iframe>
Is it possible to use jQuery or Javascript to find the links to mydomain.com with that one class and add a new window attribute to them? Or is there a better way? Thanks
Without some code I don't know the exact structure of your code, but I this could do the job. It requires jQuery to be in the iframe too.
$('iframe')[0].$('.av_buy_now').filter(function() {
return $(this).attr('href').indexOf('mydomain.com') > -1;
}).attr('target', '_blank');
You can change it if some how you can manage to execute this kind of code, changing class is little troublesome, of you got an id on it do something like this.
PAGE.html:
<button onclick="openinnewwin()">Get It</button>
<iframe src="test.html" id="ifrm"></iframe>
<script language="javascript">
function openinnewwin(){
ob=document.getElementById('ifrm');
if ( ob.contentDocument ) {
ob.contentDocument.getElementById('a').target="_blank";
}else if ( ob.contentWindow ){
ob.contentWindow.getElementById('a').target="_blank";
}
}
</script>
test.html:
Hello

get the parent url of iframe in PHP

I am creating a widget that would load in a IFrame and users will be able to place the widget on their own website. How would I get the URL of the website that is using the IFrame in javascript and/or PHP? The IFrame loads a php file.
I have tried "parent.top.location.href" and "parent.document.referrer" in the IFrame page but that is undefined.
I have also tried to echo "$_Server[referrer]" in the IFrame page and that did return the IFrame parent URL, but how easy is it for someone to manipulate the referrer variable? I dont want to get misleading information.
The Goal: I created a widget and want to allow registered users to use that widget on their site. I want to be able to find out who is using the widget and if a un-registered user is using it on their site, then the widget would not display
I have also tried to echo
"$_Server[referrer]" in the IFrame
page and that did return the IFrame
parent URL, but how easy is it for
someone to manipulate the referrer
variable?
Pretty easy, but so is disabling JavaScript! However, if a web site uses your <iframe> it will be a little difficult for them to fake the referrer in their visitor's UA. (They could also proxy your content if they really insist on hiding the fact that they're using your content. In that case your only choice is not to publish it in the first place.)
In order to present content for "partners" only you could consider providing them with a token (like Twitter/Google/... APIs). If no (or an invalid) token is used, present an error. If a valid token is used but the referrer is suspicious you should investigate further.
Try with:
parent.location.href;
or
parent.document.URL
You can use the following PHP code to have the parent window URL get values in an array:
<?php
//Getting the parent window parameters
$getURLVar = str_replace("?","",strrchr($_SERVER['HTTP_REFERER'],"?"));
$getURLVar = str_replace("&","=",$getURLVar);
$getURLVar = str_getcsv($getURLVar,"=");
$i=0;
foreach ($getURLVar as $value)
{
if ($i % 2)
$value1[$i]=$value;
else
$value2[$i]=$value;
$i++;
}
$getURLVar =array_combine($value2,$value1);
print_r($getURLVar);
?>
A small piece of JavaScript in the iframe-d page can 'un-frame' the page:
if (top != self) {top.location.replace(self.location.href);}
Otherwise, as #mck89 says: the iframe can access the URL of the parent page using the top.location.href.
Further reading on the question How to prevent my site page to be loaded via 3rd party site frame of iframe.
Assuming your widget's URL doesn't do any redirects, etc., you should be able to use:
document.referrer
from within the javascript inside your iframe and it should contain the URL of the parent page. This seems to be what YouTube does for tracking in their iframe embed codes.
I would use:
$qStr = explode('?', $_SERVER['HTTP_REFERER']);
$t= explode('&', $qStr[1]);
foreach ($t as $val)
{
$a = explode('=', $val);
$args[$a[0]]=$a[1];
}
// to check the arguments
print_r($args);
// to check the url
echo $qStr[0];
$args would contain my security token which would be checked by some hashing against the url

Categories