Using TargetLink to open new tab - javascript

// ==/UserScript==
//--- Note that the contains() text is case-sensitive.
var TargetLink = $("a:contains('We love potatoes')")
if (TargetLink && TargetLink.length)
window.location.href = TargetLink[0].href
I want to have the links it finds open in a new tab in chrome.
This may be obvious to some but I can't figure it for the life of me, can someone assist me?

Instead of changing the location of the current window, you could use something like window.open() to open a new window instead:
window.open(TargetLink[0].href, "myWindow");
Notice that popup-blockers etc. may prevent the window from being opened.
Side note:
MDN offer a quite extensive read on the use of this, and the general opinion is to avoid resorting to window.open(), for the purpose of usability. Most modern browsers use tabbed browsing, and opening up pages in new windows takes a step away from that.

Use the following code:
var TargetLink = $("a:contains('We love potatoes')"); // this will select your node
if (TargetLink && TargetLink.length) { //checks it node was there
alert("Going to redirect"); //Just to make sure that we did correct!
TargetLink.attr('taget', '_blank'); //add target="_blank"
//TargetLink.click(); // This is not working, because of a security issue.
}
And also notice about ;.

You don't need if checks, just use attr method:
$("a:contains('We love potatoes')").attr('target', '_blank');
So target="_blank" will be added to We love potatoes-links.
Demo: http://jsfiddle.net/qtsWs/

Related

Featherlight.js - how to update properties on already open featherlight iframe

I am opening a new featherlight iframe like this:
$.featherlight({
iframe:href,
iframeWidth:$(window).width(),
iframeHeight:$(window).height(),
openSpeed:0,
beforeClose:myBeforeCloseCallback
});
How can I later update the properties of the open featherlight window (such as beforeClose) and load a new URL? I'm guessing I start with $.featherlight.current();, but what next?
That would be a good feature to add. There's no such feature right now though.
You could do $.featherlight.current().setContent($('<b>example</b>')), for example.
Here's how we do it in the gallery
Simplest code that would work would look like: (not tested)
var fl = $.featherlight.current();
fl.iframe = "new url";
var $newContent = ;
$.when(fl.getContent(), function($content) {
fl.setContent($content)
});
Feel free to open an issue, or even better a PR...

Gracefully Handle Tel URL

I have a link on my website:
call me, maybe
That's great for browsers that can initiate calls but it degrades with the elegance of a hippopotamus. Something like:
<h1>The address wasn't understood</h1>
I thought of attaching on onclick listener and showing a popup with the number. However, although the listener runs, the browser still follows the url (and so shows the error) and I don't think there's a reliable way to detect whether there's a tel: protocol handler.
Is there a good solution to this?
I think something like this would work where you look to see if the device automatically wraps a telephone number.
<div id="testTel" style="display:none">+1 (111) 111-1111</div>
var isTelSupported = (function () {
var div = document.querySelector("#testTel"),
hasAnchor = document.getElementsByTagName("a").length > 0;
div.parentNode.removeChild(div);
return hasAnchor;
}());
alert(isTelSupported);

How to make the browser remember what the user choose?

I have this code. I don't really know anything about Javascript so I pretty much found it on the internet. What it does basically is closes the big header image at the top of the page. I want to know how do I make it so that the browser remembers what the user has chosen? FOr example if the person clicks to hide it and then you reload the page, it should remain hidden and not default to the original.
<script language='javascript'>
function toggle() {
var pagehead = document.getElementById("HTML6");
var xbutton = document.getElementById("hide-header");
if(pagehead.style.display == "none") {
pagehead.style.display = "block";
xbutton.innerHTML = "<img border='0' src='https://lh5.googleusercontent.com/-S5r38GtSF6s/Ui04r4eS0yI/AAAAAAAADpQ/qRnrSX2MpcY/w16-h15-no/close+X.png'/>";
}
else {
pagehead.style.display = "none";
xbutton.innerHTML = "<img border='0' src='https://lh5.googleusercontent.com/-S5r38GtSF6s/Ui04r4eS0yI/AAAAAAAADpQ/qRnrSX2MpcY/w16-h15-no/close+X.png'/>";
}
}
</script>
Not sure if it's even possible. I have no idea really.
Here is my website for reference: linkvier.com
I really hope I can get this code to work since I plan on using it on ads and stuff as well.
You need to use the browser cookies. Take a look at jQuery.cookie. There are examples there.
as far as i know http is stateless you can use cookies to get this
Read Stateless_protocol
look at checkCookie() getCookie(c_name) and setCookie(c_name,value,exdays) here #
w3schools Cookie Examples
If you don't have to support old browsers then check out html's 5 localStorage it's pretty awesome. :-)
For older browsers use cookies or one of those scripts that emulate localStorage using cookies.

getElementById from parent works for Firefox not for IE

I am trying to access an element in my Edge Animate animation (which is a menu bar) from the parent document. The element has an onClick event which is triggered depending on the #bookmark in the URL of the parent web page. My code works perfectly in Firefox but does not work in Internet Explorer(10). IE is unable to see any elements within the 'Stage' div whereas Firefox can.
This is the JavaScript code on my parent page: -
<script language='javascript'>
var thisPage = window.location.pathname;
var fullurl = document.URL;
var xxx = fullurl.substring(fullurl.indexOf('#'));
var pageString = xxx.replace("#", "");
pageString = pageString.replace("http://www.mydomain.com/portfolio/photography.html", "");
if (pageString == "corporate") {
window.onload = function() {
var iframe = document.getElementById('U10511_animation');
var innerDoc = (iframe.contentDocument) ?
iframe.contentDocument : iframe.contentWindow.document;
var corporateRectangle = innerDoc.getElementById('Stage_Corporate_Rectangle');
corporateRectangle.click();
}
};
</script>
The above code will select the Corporate tab in the menu when viewed in Firefox but not IE when the URL has the suffix #corporate.
When I insert an 'alert' for the variable 'corporateRectangle' in Firefox it returns [HTMLObj] and in IE it returns 'null'.
Any ideas anyone? Thanks.
Have you tried checking the console for an error of some sort to help you and us understand the error?
IE JavaScript often works differently than in other browsers. And iframes are particularly problematical. One possibility is that you are getting the wrong document, such that the documentyou are retrieving either does not exist or does not contain the element you are looking for. So you just have to do some debugging. Here is how I would proceed. Run your script in IE.
1) Determine whether innerDoc is iframe.contentDocument or iframe.contentWindow.document. Make sure innerDoc is not null. If it is, try to get the document a different way.
2) Assuming innerDoc is not null, enumerate all of the elements in innerDoc. You can do that as follows:
for(i = 0; i < innerDoc.all.length; i++) alert(innerDoc.all [i].id);
Make sure that the id you are looking for is actually in the document. I suspect it isn't and that you need to get a different document object under IE.
I assume you are stuck with having to use iframes. If not, I suggest you use a different approach as iframes can be very problematical and browser-specific in how they work.
internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.
You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2)
override IE's native getElementById-method.
Read more about it here.
Ok... thanks to everyone who left suggestions.
The issue was that the menu animation has a preloader. Firefox ignores the preloader whereas IE treats the preloader as onLoad being complete. Therefore the attempt to access the element ID is null as it hasn't been loaded yet.
I decided to approach the problem from a different tack and read my bookmark from within the animation. This turned out to be a very simple solution once I figured out that I had to put the code in the first frame of the animation NOT in creationComplete or compositionReady.
This was the code: -
var bookmark = parent.window.location.hash;
bookmark = bookmark.replace("#", "");
if (bookmark == "corporate") {
sym.play("corp");
}
yes, as simple as that.

AIR HTMLLoader window.open is not working

I have a web project developed in Flex which I have to make work standalone using AIR.
I created Air project and loaded the web application using flash.html.HTMLLoader.
The content is loading fine and working.
There are few buttons which open different links using javascript functions window.open.
The links are not opening. The javascript function is getting called using ExternalInterface and I placed alerts in that which is displaying.
The function contains simple window.open
window.open("http://www.google.co.in","Google");
I tried several solutions mentioned but none of them are working.
http://digitaldumptruck.jotabout.com/?p=672
http://soenkerohde.com/2008/09/air-html-with-_blank-links/
http://cookbooks.adobe.com/index.cfm?event=showdetails&postId=9243
I even tried loading a simple page in HTMLLoader component with window.open method still it is not working. On button click only alert is working but window.open is not opening the link.
<html>
<head>
<title>Test</title>
<body scroll="no">
<input type="button" value="Click" onClick="window.open('http://www.google.co.in');">
</body>
</html>
Could some one help me please
This is a radical suggestion that may or may not work, but I think it's worth a try.
Override the window.open method itself
As before, wait until the Event.COMPLETE is fired, then take it from there:
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("whatever.html");
var oldWindowOpen:Object; // save it, just in case
html.load(urlReq);
html.addEventListener(Event.COMPLETE,
function (event:Event):void {
oldWindowOpen = html.window.open;
html.window.open = asWindowOpen;
});
function asWindowOpen(href:String, name:String="_blank", specs:Object=null, replace:Object=null):void {
var urlReq = new air.URLRequest(href);
air.navigateToURL(urlReq);
}
You should probably fill out some of the function to handle the other inputs as specified in the W3Schools Reference for Window open() Method. You may have to (or want to) change all the parameter types to Object, just to be safe, since, unlike ExternalInterface interactions, the JavaScript-ActionScript types are not automatically typecast across the AIR-WebKit exchange.
The AIR Webkit environment is quite restrictive in its support for the window.open method. See Adobe documentation on Restrictions on calling the JavaScript window.open() method.
The easiest way to deal with this is just let the system's default browser open the links. Adobe documents this very question, and shows how you can pop open url's from within AIR:
var url = "http://www.adobe.com";
var urlReq = new air.URLRequest(url);
air.navigateToURL(urlReq);
Generalizing this:
function openExternalLink(href:String):void {
var urlReq = new air.URLRequest(href);
air.navigateToURL(urlReq);
}
One option: Assuming you're running jQuery on the page, you could have all the links open externally as so:
var html:HTMLLoader = new HTMLLoader();
var urlReq:URLRequest = new URLRequest("whatever.html");
html.load(urlReq);
html.addEventListener(Event.COMPLETE,
function completeHandler(event:Event):void {
html.window.jQuery('a').click(clickHandler);
});
function clickHandler( e:Object ):void {
if (e.target && e.target.href) {
openExternalLink(e.target.href);
}
e.preventDefault();
}
For more on handling DOM Events in ActionScript, see the relevant Adobe Documentation.
None of that is tested, but hopefully it gives a rough outline.
Otherwise, if you are trying to do something fancy, like pop up AIR windows with HTMLLoader frames in them, I did find one blog post discussing that: Opening links in AIR’s HTML loader

Categories