首页 > 解决方案 > Chrome 扩展 - 转换为 bitly 并复制

问题描述

我已经把这段代码放在一起,在我的(空)经验中应该接近做我需要的(将utm添加到当前链接,将其转换为bitly,然后复制到剪贴板)

我尝试尽可能多地进行调试,但正如我所说,我不是 Javascript 专家,而且 cuold 还没有走得很远,也无法从 Chrome 上的 Devtools 进行故障排除,因为它是一个扩展,但基本上我得到了正确的地址但是(html 有一个带有正确地址的弹出窗口)它没有将任何内容复制到剪贴板。我做错了什么?(这段代码是其他来源的混合,正如我所说我不知道​​ javascript,我主要使用 python,我也没有专家。Script.js:

window.onload = function() {
    function ShortLinkBitly( pLongUrl ) { /*pLongUrl is the long URL*/
    if ( !pLongUrl.match(/(ftp|http|https):\/\//i) ) {
        return "Error: Link must start with a protocol (e.g.: http or https).";
    }
    var apiKey = 'XXXXXXXXXXXXXXXXXXXXXX';
    var username = 'XXXXXXX';
    /*Ajax call*/
    $.ajax(
    {
        url: 'https://api-ssl.bitly.com/v3/shorten?login=' + username + '&apiKey=' + apiKey + '&format=json&longUrl=' + encodeURIComponent(pLongUrl),
        dataType: 'jsonp',
        success: function( response ) {
            if ( response.status_code == 500) {
                /*500 status code means the link is malformed.*/
                return "Error: Invalid link.";
            } else if ( response.status_code != 200) {

                /*If response is not 200 then an error ocurred. It can be a network issue or bitly is down.*/
                return "Error: Service unavailable.";

                /*Uncomment the following line only for debugging purposes*/
                /*console.log('Response: ' + response.status_code + '-' + response.status_txt);*/
            }
            else
                return response.data.url; /* OK, return the short link */
        },

        contentType: 'application/json'
    });
}
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    var urlArea = document.getElementById("urlArea");       
    urlArea.innerHTML = tabs[0].url.concat("?utm_medium=callcenter&utm_source=callcenter&utm_campaign=TestMauro");
    var URL = urlArea.innerHTML
    URL = ShortLinkBitly(URL)
        var dummy = document.createElement("input");
    document.body.appendChild(dummy);
    dummy.setAttribute('value', URL);
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
    document.getElementById("title").innerHTML = "Link copied successfully";
    });
}

索引.html:

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="scripts.js"></script>
</head>
<body>
<h3 id="title">Copylink</h3>
<textarea id="urlArea"></textarea>
</body>
</html>

我还检查了我的 bitly 帐户,并没有创建任何地址,所以很明显有些东西在那里不起作用?谢谢大家!

标签: javascriptgoogle-chrome-extension

解决方案


推荐阅读