最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ext.js - Open all external links in a new tab - Stack Overflow

programmeradmin4浏览0评论

Maybe somebody has already faced with this problem.
I need to make all external links to open in a new browser tab.

The solution seems to be easy: just adding target="_blank" to each link with external domain, but how can I implement it in a nice way, because whole app is written in Ext.js.

Maybe somebody has already faced with this problem.
I need to make all external links to open in a new browser tab.

The solution seems to be easy: just adding target="_blank" to each link with external domain, but how can I implement it in a nice way, because whole app is written in Ext.js.

Share Improve this question asked Mar 25, 2014 at 8:22 Pavel TitenkovPavel Titenkov 1181 gold badge2 silver badges7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You change target attributes with JavaScript:

var tlinks = document.getElementsByTagName('a');
    for (var i=0;i<tlinks.length;i++){
        if (tlinks[i].href.indexOf('http://www.yourownurlhere.') == -1) {
            tlinks[i].setAttribute('target', '_blank');
        }                
    }

Remember to replace "yourownurlhere." with your actual url

The trick can be done with event delegation.

Ext.select('body').on('click', function (e, el) {
    el.target = '_blank';
}, null, {delegate: 'a'});

Note that if you write just

Ext.select('a').on('click', function (e, el) {
    el.target = '_blank';
});

then you apply handler only to existing links. However, delegation also handles elements created afterwards. If you want such behaivor for links included only in certain container, you may change 'body' to any selector that matches that container.

Here is jsfiddle

You can simply do :

window.open("Your link");

I decided to answer my own question, because maybe it will be useful for anybody. The only way to catch all clicks on the links is to control body clicks (as triclozan wrote in his answer).

This code will modify every link after clicking and will open it in the new window:

Ext.getBody().addListener('click', function (event, el) {
    var clickTarget = event.target;

    if (clickTarget.href && clickTarget.href.indexOf(window.location.origin) === -1) {
        clickTarget.target = "_blank";
    }
});

Hope this code will save few hours of googling for somebody with the same problem :)

发布评论

评论列表(0)

  1. 暂无评论