0

I am developing a small Chrome extension in which i am not able to get the current URL of tab.

Below is the JS code this if(tab_id.includes("facebook")) not working:

var tab_id = null;

function click(e) {
    chrome.tabs.getCurrent(function (tab) {
        tab_id = tab.url;
        window.alert(tab_id);
    });
    if (tab_id.includes("facebook")) {
        chrome.tabs.executeScript(null,
            {
                code: "try {document.querySelector('[type=password]').value ='10p14ej0016_';" +
                "document.querySelector('[type=email]').value = '97sujeetkumar@gmail.com';" +
                "}catch(e){}"
            });
        window.close();

    }
}

document.addEventListener('DOMContentLoaded', function () {
    var divs = document.querySelectorAll('Button');
    for (var i = 0; i < divs.length; i++) {
        divs[i].addEventListener('click', click);
    }
});
DimaSan
  • 12,264
  • 11
  • 65
  • 75
Anjali Sharma
  • 57
  • 2
  • 7
  • Please [edit] the question to be on-topic: include a **complete** [mcve] that duplicates the problem. Usually, including a *manifest.json*, some of the background *and* content scripts. Questions seeking debugging help ("**why isn't this code working?**") must include: ►the desired behavior, ►a specific problem or error *and* ►the shortest code necessary to reproduce it **in the question itself**. Questions without a clear problem statement are not useful to other readers. See: "**How to create a [mcve]**", [What topics can I ask about here?](http://stackoverflow.com/help/on-topic), and [ask]. – Makyen Oct 29 '16 at 18:52
  • Does your *manifest.json* include the `tabs` permission? This permission is required for the `url` to be included in the [Tab object](https://developer.chrome.com/extensions/tabs#type-Tab). On the other hand, this is actually a return value from asynchronous call issue. – Makyen Oct 29 '16 at 18:54
  • Where are you executing this code? In a popup? – Makyen Oct 29 '16 at 19:01
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Makyen Oct 29 '16 at 19:02
  • The callback function of `chrome.tabs.getCurrent` is executed asynchronously. Therefore, the line `if (tas_id.includes("facebook"))` is executed while `tab_id` is still null. Review asynchronous concepts – Iván Nokonoko Oct 29 '16 at 19:47

0 Answers0