Javascript in .js file, detecting presence of link in parent html
I am making some link bait which is basically an externally hosted .js file people can place on their websites. I would like an accompanyi开发者_JAVA技巧ng html link to accompany the widget however I would like the widget to detect if the link is present. i.e.
<script src="http://domain.com/foo.js"></script><br />
by <a href="http://domain.com">My Site</a> <-- detect this is here
The issue is that i dont know on which sites my widget will be placed.
any ideas?
var l = document.links, myLinkTest = false;
var linkcount = l.length;
while(linkcount > 0 && !myLinkTest) {
if(l[linkcount-1].href == "http://domain.com"){myLinkTest = true;}
linkcount --;
}
var widget = function(){
if(myLinkTest){
//do stuff
}
}();
Test all links on page and only run script function if your link is found?
You could look up all anchor elements and verify that an anchor with that href is there or verify with other criteria.
var isMyLinkPresent = function () {
var anchors = document.getElementsByTagName('a');
for (i = 0; i < anchors.length; i++) {
if(anchors[i].attr('href') === "http://domain.com") {
return true;
}
};
return false;
}
//in case you want to notify you own server of the presence, this will send a request to your server for picking up which site actually has the link
(function () {
if (isMyLinkPresent()) {
var script = document.createElement('script');
script.attr('src', 'http://domain.com/tellmewhichsitehasit?site=' + window.location.host)
document.head.appenChild(script);
}
})();
Alternatively you could put the link yourself with javascript, but then you have to have some api the webmaster will use. Ex in the 'src' attribute of the script you can add parameters , you can then pick that up when generating the javascript or interpret it by looking at src.
精彩评论