stackoverflow.com Open in urlscan Pro
151.101.65.69  Public Scan

URL: https://stackoverflow.com/questions/18436245/how-to-fetch-url-of-current-tab-in-my-chrome-extension-using-javascript
Submission Tags: falconsandbox
Submission: On November 22 via api from US — Scanned from DE

Form analysis 2 forms found in the DOM

/search

<form id="search" role="search" action="/search" class="flex--item fl-grow1 searchbar px12 js-searchbar " autocomplete="off">
  <div class="ps-relative">
    <input name="q" type="text" placeholder="Search…" value="" autocomplete="off" maxlength="240" class="s-input s-input__search js-search-field " aria-label="Search" aria-controls="top-search" data-controller="s-popover"
      data-action="focus->s-popover#show" data-s-popover-placement="bottom-start">
    <svg aria-hidden="true" class="s-input-icon s-input-icon__search svg-icon iconSearch" width="18" height="18" viewBox="0 0 18 18">
      <path d="m18 16.5-5.14-5.18h-.35a7 7 0 10-1.19 1.19v.35L16.5 18l1.5-1.5ZM12 7A5 5 0 112 7a5 5 0 0110 0Z"></path>
    </svg>
    <div class="s-popover p0 wmx100 wmn4 sm:wmn-initial js-top-search-popover" id="top-search" role="menu">
      <div class="s-popover--arrow"></div>
      <div class="js-spinner p24 d-flex ai-center jc-center d-none">
        <div class="s-spinner s-spinner__sm fc-orange-400">
          <div class="v-visible-sr">Loading…</div>
        </div>
      </div>
      <span class="v-visible-sr js-screen-reader-info"></span>
      <div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
      <div class="js-search-hints" aria-describedby="Tips for searching"></div>
    </div>
  </div>
</form>

POST /questions/18436245/answer/submit

<form id="post-form" action="/questions/18436245/answer/submit" method="post" class="js-add-answer-component post-form">
  <input type="hidden" id="post-id" value="18436245">
  <input type="hidden" id="qualityBanWarningShown" name="qualityBanWarningShown" value="false">
  <input type="hidden" name="referrer" value="">
  <h2 class="space"> Your Answer </h2>
  <script>
    StackExchange.ifUsing("editor", function() {
      StackExchange.using("externalEditor", function() {
        StackExchange.using("snippets", function() {
          StackExchange.snippets.init();
        });
      });
    }, "code-snippets");
  </script>
  <script>
    StackExchange.ready(function() {
      var channelOptions = {
        tags: "".split(" "),
        id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);
      StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
            createEditor();
          });
        } else {
          createEditor();
        }
      });

      function createEditor() {
        StackExchange.prepareEditor({
          useStacksEditor: false,
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
            brandingHtml: "Powered by \u003ca href=\"https://imgur.com/\"\u003e\u003csvg class=\"svg-icon\" width=\"50\" height=\"18\" viewBox=\"0 0 50 18\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"\u003e\u003cpath d=\"M46.1709 9.17788C46.1709 8.26454 46.2665 7.94324 47.1084 7.58816C47.4091 7.46349 47.7169 7.36433 48.0099 7.26993C48.9099 6.97997 49.672 6.73443 49.672 5.93063C49.672 5.22043 48.9832 4.61182 48.1414 4.61182C47.4335 4.61182 46.7256 4.91628 46.0943 5.50789C45.7307 4.9328 45.2525 4.66231 44.6595 4.66231C43.6264 4.66231 43.1481 5.28821 43.1481 6.59048V11.9512C43.1481 13.2535 43.6264 13.8962 44.6595 13.8962C45.6924 13.8962 46.1709 13.2535 46.1709 11.9512V9.17788Z\"/\u003e\u003cpath d=\"M32.492 10.1419C32.492 12.6954 34.1182 14.0484 37.0451 14.0484C39.9723 14.0484 41.5985 12.6954 41.5985 10.1419V6.59049C41.5985 5.28821 41.1394 4.66232 40.1061 4.66232C39.0732 4.66232 38.5948 5.28821 38.5948 6.59049V9.60062C38.5948 10.8521 38.2696 11.5455 37.0451 11.5455C35.8209 11.5455 35.4954 10.8521 35.4954 9.60062V6.59049C35.4954 5.28821 35.0173 4.66232 34.0034 4.66232C32.9703 4.66232 32.492 5.28821 32.492 6.59049V10.1419Z\" /\u003e\u003cpath fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M25.6622 17.6335C27.8049 17.6335 29.3739 16.9402 30.2537 15.6379C30.8468 14.7755 30.9615 13.5579 30.9615 11.9512V6.59049C30.9615 5.28821 30.4833 4.66231 29.4502 4.66231C28.9913 4.66231 28.4555 4.94978 28.1109 5.50789C27.499 4.86533 26.7335 4.56087 25.7005 4.56087C23.1369 4.56087 21.0134 6.57349 21.0134 9.27932C21.0134 11.9852 23.003 13.913 25.3754 13.913C26.5612 13.913 27.4607 13.4902 28.1109 12.6616C28.1109 12.7229 28.1161 12.7799 28.121 12.8346C28.1256 12.8854 28.1301 12.9342 28.1301 12.983C28.1301 14.4373 27.2502 15.2321 25.777 15.2321C24.8349 15.2321 24.1352 14.9821 23.5661 14.7787C23.176 14.6393 22.8472 14.5218 22.5437 14.5218C21.7977 14.5218 21.2429 15.0123 21.2429 15.6887C21.2429 16.7375 22.9072 17.6335 25.6622 17.6335ZM24.1317 9.27932C24.1317 7.94324 24.9928 7.09766 26.1024 7.09766C27.2119 7.09766 28.0918 7.94324 28.0918 9.27932C28.0918 10.6321 27.2311 11.5116 26.1024 11.5116C24.9737 11.5116 24.1317 10.6491 24.1317 9.27932Z\"/\u003e\u003cpath d=\"M16.8045 11.9512C16.8045 13.2535 17.2637 13.8962 18.2965 13.8962C19.3298 13.8962 19.8079 13.2535 19.8079 11.9512V8.12928C19.8079 5.82936 18.4879 4.62866 16.4027 4.62866C15.1594 4.62866 14.279 4.98375 13.3609 5.88013C12.653 5.05154 11.6581 4.62866 10.3573 4.62866C9.34336 4.62866 8.57809 4.89931 7.9466 5.5079C7.58314 4.9328 7.10506 4.66232 6.51203 4.66232C5.47873 4.66232 5.00066 5.28821 5.00066 6.59049V11.9512C5.00066 13.2535 5.47873 13.8962 6.51203 13.8962C7.54479 13.8962 8.0232 13.2535 8.0232 11.9512V8.90741C8.0232 7.58817 8.44431 6.91179 9.53458 6.91179C10.5104 6.91179 10.893 7.58817 10.893 8.94108V11.9512C10.893 13.2535 11.3711 13.8962 12.4044 13.8962C13.4375 13.8962 13.9157 13.2535 13.9157 11.9512V8.90741C13.9157 7.58817 14.3365 6.91179 15.4269 6.91179C16.4027 6.91179 16.8045 7.58817 16.8045 8.94108V11.9512Z\"/\u003e\u003cpath d=\"M3.31675 6.59049C3.31675 5.28821 2.83866 4.66232 1.82471 4.66232C0.791758 4.66232 0.313354 5.28821 0.313354 6.59049V11.9512C0.313354 13.2535 0.791758 13.8962 1.82471 13.8962C2.85798 13.8962 3.31675 13.2535 3.31675 11.9512V6.59049Z\" /\u003e\u003cpath d=\"M1.87209 0.400291C0.843612 0.400291 0 1.1159 0 1.98861C0 2.87869 0.822846 3.57676 1.87209 3.57676C2.90056 3.57676 3.7234 2.87869 3.7234 1.98861C3.7234 1.1159 2.90056 0.400291 1.87209 0.400291Z\" fill=\"#1BB76E\"/\u003e\u003c/svg\u003e\u003c/a\u003e",
            contentPolicyHtml: "User contributions licensed under \u003ca href=\"https://stackoverflow.com/help/licensing\"\u003ecc by-sa\u003c/a\u003e \u003ca href=\"https://stackoverflow.com/legal/content-policy\"\u003e(content policy)\u003c/a\u003e",
            allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer",
          immediatelyShowMarkdownHelp: true,
          enableTables: true,
          enableSnippets: true
        });
      }
    });
  </script>
  <div id="post-editor" class="post-editor js-post-editor">
    <div class="ps-relative">
      <div class="wmd-container mb8">
        <div id="wmd-button-bar" class="wmd-button-bar btr-sm">
          <ul id="wmd-button-row" class="wmd-button-row">
            <li id="wmd-bold-button" class="wmd-button" style="left: 0px;"><span style="background-position: 0px -20px;"></span></li>
            <li id="wmd-italic-button" class="wmd-button" style="left: 25px;"><span style="background-position: -20px -20px;"></span></li>
            <li id="wmd-spacer1" class="wmd-spacer" style="left: 50px;"><span style="background-position: -40px -20px;"></span></li>
            <li id="wmd-link-button" class="wmd-button" style="left: 75px;"><span style="background-position: -40px -20px;"></span></li>
            <li id="wmd-quote-button" class="wmd-button" style="left: 100px;"><span style="background-position: -60px -20px;"></span></li>
            <li id="wmd-code-button" class="wmd-button" style="left: 125px;"><span style="background-position: -80px -20px;"></span></li>
            <li id="wmd-image-button" class="wmd-button" style="left: 150px;"><span style="background-position: -100px -20px;"></span></li>
            <li id="wmd-spacer2" class="wmd-spacer" style="left: 175px;"><span style="background-position: -120px -20px;"></span></li>
            <li id="wmd-olist-button" class="wmd-button" style="left: 200px;"><span style="background-position: -120px -20px;"></span></li>
            <li id="wmd-ulist-button" class="wmd-button" style="left: 225px;"><span style="background-position: -140px -20px;"></span></li>
            <li id="wmd-heading-button" class="wmd-button" style="left: 250px;"><span style="background-position: -160px -20px;"></span></li>
            <li id="wmd-hr-button" class="wmd-button" style="left: 275px;"><span style="background-position: -180px -20px;"></span></li>
            <li id="wmd-spacer3" class="wmd-spacer" style="left: 300px;"><span style="background-position: -200px -20px;"></span></li>
            <li id="wmd-undo-button" class="wmd-button" style="left: 325px;"><span style="background-position: -200px -20px;"></span></li>
            <li id="wmd-redo-button" class="wmd-button" style="left: 350px;"><span style="background-position: -220px -20px;"></span></li>
            <li class="wmd-spacer wmd-spacer-max"></li>
          </ul>
        </div>
        <div class="js-stacks-validation">
          <div class="ps-relative">
            <textarea id="wmd-input" name="post-text" class="wmd-input s-input bar0 js-post-body-field" data-post-type-id="2" cols="92" rows="15" tabindex="101" data-min-length=""></textarea>
          </div>
          <div class="s-input-message mt4 d-none js-stacks-validation-message"></div>
        </div>
      </div>
    </div>
    <aside class="d-flex ai-start jc-space-between js-answer-help s-notice s-notice__warning pb0 pr4 pt4 mb8 d-none" role="status" aria-hidden="true">
      <div class="flex--item pt8">
        <p>Thanks for contributing an answer to Stack Overflow!</p>
        <ul>
          <li>Please be sure to <em>answer the question</em>. Provide details and share your research!</li>
        </ul>
        <p>But <em>avoid</em> …</p>
        <ul>
          <li>Asking for help, clarification, or responding to other answers.</li>
          <li>Making statements based on opinion; back them up with references or personal experience.</li>
        </ul>
        <p>To learn more, see our <a href="/help/how-to-answer">tips on writing great answers</a>.</p>
      </div>
      <button class="flex--item js-answer-help-close-btn s-btn s-btn__muted fc-dark">
        <svg aria-hidden="true" class="svg-icon iconClear" width="18" height="18" viewBox="0 0 18 18">
          <path d="M15 4.41 13.59 3 9 7.59 4.41 3 3 4.41 7.59 9 3 13.59 4.41 15 9 10.41 13.59 15 15 13.59 10.41 9 15 4.41Z"></path>
        </svg>
      </button>
    </aside>
    <div>
      <div id="draft-saved" class="fc-success h24" style="display:none;">Draft saved</div>
      <div id="draft-discarded" class="fc-error h24" style="display:none;">Draft discarded</div>
    </div>
    <div id="wmd-preview" class="s-prose mb16 wmd-preview js-wmd-preview"></div>
    <div></div>
    <div class="edit-block">
      <input id="fkey" name="fkey" type="hidden" value="c1b9cf13e4db159a5a5622eafb21dde204f2de7afbbe05301b695ad0cf3656be">
      <input id="author" name="author" type="text">
    </div>
  </div>
  <div class="ps-relative">
    <div class="form-item new-post-login p0 my16">
      <div class="d-flex gs16 md:fd-column new-login-form">
        <div class="d-flex fd-column w50 md:w-auto gsy gs8 jc-space-between new-login-left">
          <h3 class="flex--item fs-title">Sign up or
            <a id="login-link" href="/users/login?ssrc=question_page&amp;returnurl=https%3a%2f%2fstackoverflow.com%2fquestions%2f18436245%2fhow-to-fetch-url-of-current-tab-in-my-chrome-extension-using-javascript%23new-answer">log in</a></h3>
          <script>
            StackExchange.ready(function() {
              StackExchange.helpers.onClickDraftSave('#login-link');
            });
          </script>
          <div class="flex--item s-btn s-btn__muted s-btn__outlined s-btn__icon google-login" data-ga="[&quot;sign up&quot;,&quot;Sign Up Started - Google&quot;,&quot;New Post&quot;,null,null]">
            <svg aria-hidden="true" class="native svg-icon iconGoogle" width="18" height="18" viewBox="0 0 18 18">
              <path d="M16.51 8H8.98v3h4.3c-.18 1-.74 1.48-1.6 2.04v2.01h2.6a7.8 7.8 0 002.38-5.88c0-.57-.05-.66-.15-1.18Z" fill="#4285F4"></path>
              <path d="M8.98 17c2.16 0 3.97-.72 5.3-1.94l-2.6-2a4.8 4.8 0 01-7.18-2.54H1.83v2.07A8 8 0 008.98 17Z" fill="#34A853"></path>
              <path d="M4.5 10.52a4.8 4.8 0 010-3.04V5.41H1.83a8 8 0 000 7.18l2.67-2.07Z" fill="#FBBC05"></path>
              <path d="M8.98 4.18c1.17 0 2.23.4 3.06 1.2l2.3-2.3A8 8 0 001.83 5.4L4.5 7.49a4.77 4.77 0 014.48-3.3Z" fill="#EA4335"></path>
            </svg> Sign up using Google
          </div>
          <div class="flex--item s-btn s-btn__muted s-btn__icon facebook-login" data-ga="[&quot;sign up&quot;,&quot;Sign Up Started - Facebook&quot;,&quot;New Post&quot;,null,null]">
            <svg aria-hidden="true" class="svg-icon iconFacebook" width="18" height="18" viewBox="0 0 18 18">
              <path d="M3 1a2 2 0 00-2 2v12c0 1.1.9 2 2 2h12a2 2 0 002-2V3a2 2 0 00-2-2H3Zm6.55 16v-6.2H7.46V8.4h2.09V6.61c0-2.07 1.26-3.2 3.1-3.2.88 0 1.64.07 1.87.1v2.16h-1.29c-1 0-1.19.48-1.19 1.18V8.4h2.39l-.31 2.42h-2.08V17h-2.5Z"
                fill="#4167B2"></path>
            </svg> Sign up using Facebook
          </div>
          <div class="flex--item s-btn s-btn__muted s-btn__outlined s-btn__icon stackexchange-login" data-ga="[&quot;sign up&quot;,&quot;Sign Up Navigation&quot;,&quot;New Post&quot;,null,null]">
            <svg aria-hidden="true" class="native svg-icon iconLogoGlyphXSm" width="18" height="18" viewBox="0 0 18 18">
              <path d="M14 16v-5h2v7H2v-7h2v5h10Z" fill="#BCBBBB"></path>
              <path d="m12.09.72-1.21.9 4.5 6.07 1.22-.9L12.09.71ZM5 15h8v-2H5v2Zm9.15-5.87L8.35 4.3l.96-1.16 5.8 4.83-.96 1.16Zm-7.7-1.47 6.85 3.19.63-1.37-6.85-3.2-.63 1.38Zm6.53 5L5.4 11.39l.38-1.67 7.42 1.48-.22 1.46Z" fill="#F48024"></path>
            </svg> Sign up using Email and Password
          </div>
        </div>
        <input type="hidden" name="use-facebook" class="use-facebook" value="false">
        <input type="hidden" name="use-google" class="use-google" value="false">
        <button type="button" class="d-none js-submit-openid">Submit</button>
        <div class="d-flex gsy gs8 fd-column w50 md:w-auto new-login-right form-item p0">
          <h3 class="flex--item fs-title">Post as a guest</h3>
          <div class="flex--item">
            <div class="d-flex gs4 gsy fd-column">
              <label class="s-label" for="display-name">Name</label>
              <div class="d-flex ps-relative">
                <input class="s-input" id="display-name" name="display-name" maxlength="30" type="text" value="" tabindex="105" placeholder="">
              </div>
            </div>
          </div>
          <div class="flex--item">
            <div class="d-flex gs4 gsy fd-column">
              <div class="flex--item">
                <div class="d-flex gs2 gsy fd-column">
                  <label class="flex--item s-label" for="m-address">Email</label>
                  <p class="flex--item s-description">Required, but never shown</p>
                </div>
              </div>
              <div class="d-flex ps-relative">
                <input class="s-input js-post-email-field" id="m-address" name="m-address" type="text" value="" size="40" tabindex="106" placeholder="">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <script>
      StackExchange.ready(function() {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f18436245%2fhow-to-fetch-url-of-current-tab-in-my-chrome-extension-using-javascript%23new-answer', 'question_page');
      });
    </script>
    <noscript>
      <h3 class="flex--item fs-title">Post as a guest</h3>
      <div class="flex--item">
        <div class="d-flex gs4 gsy fd-column">
          <label class="s-label" for="display-name">Name</label>
          <div class="d-flex ps-relative">
            <input class="s-input" id="display-name" name="display-name" maxlength="30" type="text" value="" tabindex="105" placeholder="">
          </div>
        </div>
      </div>
      <div class="flex--item">
        <div class="d-flex gs4 gsy fd-column">
          <div class="flex--item">
            <div class="d-flex gs2 gsy fd-column">
              <label class="flex--item s-label" for="m-address">Email</label>
              <p class="flex--item s-description">Required, but never shown</p>
            </div>
          </div>
          <div class="d-flex ps-relative">
            <input class="s-input js-post-email-field" id="m-address" name="m-address" type="text" value="" size="40" tabindex="106" placeholder="">
          </div>
        </div>
      </div>
    </noscript>
  </div>
  <div class="form-submit cbt d-flex gsx gs4">
    <button id="submit-button" class="flex--item s-btn s-btn__primary s-btn__icon" type="submit" tabindex="120" autocomplete="off"> Post Your Answer </button>
    <button class="flex--item s-btn s-btn__danger discard-answer dno"> Discard </button>
    <p class="privacy-policy-agreement"> By clicking “Post Your Answer”, you agree to our <a href="https://stackoverflow.com/legal/terms-of-service/public" name="tos" target="_blank" class="-link">terms of service</a>,
      <a href="https://stackoverflow.com/legal/privacy-policy" name="privacy" target="_blank" class="-link">privacy policy</a> and
      <a href="https://stackoverflow.com/legal/cookie-policy" name="cookie" target="_blank" class="-link">cookie policy</a><input type="hidden" name="legalLinksShown" value="1">
    </p>
  </div>
  <div class="js-general-error general-error cbt d-none"></div>
</form>

Text Content

Stack Overflow
 1. About
 2. Products
 3. For Teams

 1. Stack Overflow Public questions & answers
 2. Stack Overflow for Teams Where developers & technologists share private
    knowledge with coworkers
 3. Jobs Programming & related technical career opportunities
 4. Talent Recruit tech talent & build your employer brand
 5. Advertising Reach developers & technologists worldwide
 6. About the company

Loading…


 1. 
 2. Log in Sign up


 3. CURRENT COMMUNITY
    
    
     * 
       Stack Overflow
       help chat
     * 
       Meta Stack Overflow
    
    
    YOUR COMMUNITIES
    
    Sign up or log in to customize your list.
    
    
    MORE STACK EXCHANGE COMMUNITIES
    
    company blog
    

 1. Home
 2. 1. Public
    2. Questions
    3. Tags
    4. Users
    5. Collectives
       
    6. Explore Collectives
    7. Find a Job
    8. Jobs
    9. Companies
 3.    Teams
       Stack Overflow for Teams – Collaborate and share knowledge with a private
       group. Create a free Team What is Teams?
    1. Teams
       
    2. Create free Team

Collectives on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you
use most.

Learn more

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy
to search.

Learn more



HOW TO FETCH URL OF CURRENT TAB IN MY CHROME EXTENSION USING JAVASCRIPT

Ask Question
Asked 8 years, 3 months ago
Active 7 days ago
Viewed 56k times
Report this ad
This question shows research effort; it is useful and clear

30
This question does not show any research effort; it is unclear or not useful

8
Bookmark this question.

Show activity on this post.


I am just getting started with Google Chrome Extension development and my
project involves making an extension which when clicked prints the URL of
whichever page/tab is currently open.

So if I am on google's home page and I click my extension, I need to get
"https://www.google.com/" as my output within the extension.

I need to do this using javascript and am unable to find code which I understand
and which does the job. I read about using "window.location" and "document.href"
and stuff but won't that give me the url of just my extension and not the
current tab?

Please help me get started. Thanks in advance.

javascript url google-chrome-extension
Share
Share a link to this question

Copy linkCC BY-SA 3.0

Improve this question
Follow
Follow this question to receive notifications


edited Jan 7 '17 at 21:01

Chris Moschini
34.3k1818 gold badges154154 silver badges181181 bronze badges
asked Aug 26 '13 at 3:38

Darth CoderDarth Coder
1,56866 gold badges3030 silver badges5454 bronze badges
2
 * possible duplicate of How to get current URL in Chrome on click of the button
   – Rob W
   Aug 26 '13 at 12:37
 * SOLUTION: stackoverflow.com/a/58687656/6546261
   – Prem Santh
   Nov 4 '19 at 5:34

Add a comment  | 



9 ANSWERS 9

Active Oldest Votes
This answer is useful

65
This answer is not useful


Show activity on this post.


Note you must have the tabs permission set in your manifest file

"permissions": [
    "tabs"
],


http://developer.chrome.com/extensions/tabs.html

or the activeTab permission if initiated by a click on the extension button[Xan]

https://developer.chrome.com/extensions/activeTab

--------------------------------------------------------------------------------

Code:

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    console.log(tabs[0].url);
});


Share
Share a link to this answer

Copy linkCC BY-SA 4.0

Improve this answer
Follow
Follow this answer to receive notifications


edited Nov 15 at 9:37

wOxxOm
47.8k77 gold badges9393 silver badges106106 bronze badges
answered Aug 26 '13 at 3:48

MusaMusa
92.3k1717 gold badges108108 silver badges127127 bronze badges
5
 * 1
   Umm I tried the code but it's not working. This is the error I get on the
   console: Uncaught TypeError: Cannot read property 'url' of undefined
   – Darth Coder
   Aug 26 '13 at 4:25
 * Great :D The second solution works fine Thanks. Can you please explain the
   answer as well? I mean what does active:true indicate when we are already
   using currentWindow:true? also, what exactly will be the contents of tabs[] ?
   – Darth Coder
   Aug 26 '13 at 4:48
 * 1
   You can check developer.chrome.com/extensions/tabs.html#method-query for more
   details on the parameters of the function.
   – Métoule
   Aug 26 '13 at 11:27
 * 5
   Note: This no longer needs the tabs permission. If initiated by a click on
   the extension button, activeTab permission is sufficient.
   – Xan
   Aug 14 '14 at 8:19
 * 1
   tabs is such a heavy permission! Consider using: activeTab.
   – Константин Ван
   Jul 20 '16 at 12:53

Add a comment  | 

This answer is useful

33
This answer is not useful


Show activity on this post.


Using javascript, it will work if you are not using it in popup because
javascript in popup will return url of popup therefore, in popup, you have to
use Chrome tab API and set permission in Chrome manifest.

chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
    console.log(tabs[0].url);
});


So best way is to use Chrome tab API

Share
Share a link to this answer

Copy linkCC BY-SA 3.0

Improve this answer
Follow
Follow this answer to receive notifications


edited Jan 27 '14 at 21:46

Lucas
3,20266 gold badges2727 silver badges4444 bronze badges
answered Aug 26 '13 at 6:17

saadsafsaadsaf
1,36111 gold badge1515 silver badges2727 bronze badges
4
 * 4
   This is the most relevant answer and should be updated as the best answer.
   – Ben
   Oct 23 '14 at 9:07
 * @saadsaf I'm having a really hard time figuring out how to fork tabs[0].url
   out of this callback though. Should it/Can it only be used in the query's
   callback function?
   – A13X
   Mar 28 '17 at 21:04
 * @A13X Kindly elaborate what u r trying to achieve and paste some code here so
   that we can solve it efficiently together.
   – saadsaf
   Mar 29 '17 at 5:40
 * 1
   Nevermind. I was trying to set a global variable that was already declared in
   my popup.js to the tab[0].url. It kept returning undefined. I instead opted
   to directly put the query() in my window.onload and do an injection of the
   HTML doc I want (to display the url). It works.
   – A13X
   Apr 1 '17 at 0:43

Add a comment  | 
This answer is useful

8
This answer is not useful


Show activity on this post.


You need to be careful with what you mean by "current tab". If the user has more
than one window open, each of them with multiple tabs, Chrome defines the
"current window" as the one that is running the content script that makes use of
the chrome.tabs API. That happened to me and I solved it by referencing not the
"current" window but the last focused one:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
});


References:

https://developer.chrome.com/extensions/windows#current-window
https://developer.chrome.com/extensions/tabs#method-query

Hope it helps!

Share
Share a link to this answer

Copy linkCC BY-SA 3.0

Improve this answer
Follow
Follow this answer to receive notifications


edited May 8 '17 at 22:19


answered Mar 19 '15 at 17:52

Clint EastwoodClint Eastwood
4,45822 gold badges2929 silver badges2626 bronze badges
0
Add a comment  | 

This answer is useful

1
This answer is not useful


Show activity on this post.


DO NOT use getSelected

As per the Chrome Developer Docs: chrome.tabs.getSelected has been deprecated
since Chrome ver.33

Instead use:

chrome.tabs.query({active:true}, __someCallbackFunction__) like Musa's second
suggestion.

Share
Share a link to this answer

Copy linkCC BY-SA 3.0

Improve this answer
Follow
Follow this answer to receive notifications


edited Jun 20 '20 at 9:12

CommunityBot
111 silver badge
answered Jan 4 '18 at 4:20

Rich WerdenRich Werden
78599 silver badges1111 bronze badges
Add a comment  | 
This answer is useful

1
This answer is not useful


Show activity on this post.


Here is the answer your looking for without adding new tabs permissions

chrome.browserAction.onClicked.addListener(function(e){
     console.log(e.url); 
     //give you the url of the tab on which you clicked the extension
})


Share
Share a link to this answer

Copy linkCC BY-SA 4.0

Improve this answer
Follow
Follow this answer to receive notifications


answered Nov 4 '19 at 5:30

Prem SanthPrem Santh
18611 silver badge1010 bronze badges
1
 * This seems to be the most current way to implement this.
   – Tim John
   Oct 30 at 0:14

Add a comment  | 
This answer is useful

0
This answer is not useful


Show activity on this post.


UPDATE: this method is now deprecated, so please don't use it

In my case any above has not worked. So I used this:

chrome.tabs.getSelected(null, function(tab) {
    console.log(tab.url)
})


and it worked great! Hope it helps.

Share
Share a link to this answer

Copy linkCC BY-SA 3.0

Improve this answer
Follow
Follow this answer to receive notifications


edited Aug 14 '14 at 8:03


answered Feb 19 '14 at 10:08

KamilKamil
1,59522 gold badges1919 silver badges2424 bronze badges
2
 * getSelected() has been deprecated and shouldn't be used.
   chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs)
   { console.log(tabs[0].url); }); is the current way to get the current tab
   (and URL).
   – Michael Oryl
   Aug 13 '14 at 13:46
 * use 'activeTab' permission on manifest and try chrome.tabs.query({active:
   true},function(tab){console.log(tab)}) It should work Its not recommended to
   use getSelected() as its deprecated
   – Prem Santh
   Nov 4 '19 at 5:23

Add a comment  | 
This answer is useful

0
This answer is not useful


Show activity on this post.


this worked for me give it a try

chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
 });


Share
Share a link to this answer

Copy linkCC BY-SA 3.0

Improve this answer
Follow
Follow this answer to receive notifications


answered Sep 11 '15 at 18:32

jayant singhjayant singh
8591212 silver badges1616 bronze badges
Add a comment  | 
This answer is useful

0
This answer is not useful


Show activity on this post.


The solutions posted here somehow did not worked for me but below snippet worked
without any issues-

let currentURL = window.location.href;
console.log(currentURL)


Share
Share a link to this answer

Copy linkCC BY-SA 4.0

Improve this answer
Follow
Follow this answer to receive notifications


edited Jul 2 at 16:48

Dharman
24.2k2020 gold badges6464 silver badges113113 bronze badges
answered Jul 2 at 16:43

ShashirajShashiraj
6144 bronze badges
Add a comment  | 
This answer is useful

0
This answer is not useful


Show activity on this post.


Please be aware that chrome.tabs.query() and chrome.tabs.getCurrent will run
into race conditions when called in short order from multiple content scripts.

The returned tab will not necessarily be the tab of the requestor.

An easier way to do this is to send a message to the background thread. This
message includes the sending tab as the tab parameter.

The background thread can take this parameter and directly include it in its
response to the message.

Not only does this prevent race conditions, it's also faster because it does not
use an asynchronous operation (unlike the call to chrome.tabs.query())

Example:

Content script

var myTab;
chrome.runtime.sendMessage({ message: "get_tab_msg" }, (response) => {
    myTab = response.tab;
});


Background script

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.message === "get_tab_msg") {
        // The content script has asked for the tab.
        sendResponse({tab: sender.tab});
    }
});



Share
Share a link to this answer

Copy linkCC BY-SA 4.0

Improve this answer
Follow
Follow this answer to receive notifications


answered Nov 4 at 22:18

Piers Uso WalterPiers Uso Walter
32944 silver badges1010 bronze badges
Add a comment  | 


YOUR ANSWER

 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 



Thanks for contributing an answer to Stack Overflow!

 * Please be sure to answer the question. Provide details and share your
   research!

But avoid …

 * Asking for help, clarification, or responding to other answers.
 * Making statements based on opinion; back them up with references or personal
   experience.

To learn more, see our tips on writing great answers.

Draft saved
Draft discarded





SIGN UP OR LOG IN

Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Submit


POST AS A GUEST

Name

Email

Required, but never shown




POST AS A GUEST

Name

Email

Required, but never shown


Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy
policy and cookie policy




NOT THE ANSWER YOU'RE LOOKING FOR? BROWSE OTHER QUESTIONS TAGGED JAVASCRIPT URL
GOOGLE-CHROME-EXTENSION OR ASK YOUR OWN QUESTION.

   The Overflow Blog
 * Introducing Content Health, a new way to keep the knowledge base up-to-date
 * Podcast 394: what if you could invest in your favorite developer?
   Featured on Meta
 * Now live: A fully responsive profile
 * Reducing the weight of our footer

Report this ad

Check out these companies
 * ioki GmbH
   Follow
   Inspiring smart mobility - working today on the mobility of tomorrow. We are
   hiring!
   javascriptrubytypescript
   2 open jobs · 13 followers
   dismiss this company
 * DCI - Digital Career Institute gGmbH
   Follow
   At DCI/Devugees, we have set ourselves the goal of becoming the talent
   factory for young talent in the booming digital industry.
   reactjsnode.jsexpress
   1 open job · 9 followers
   dismiss this company
 * Circle
   Follow
   Our mission is to raise global economic prosperity through programmable
   internet commerce.
   javascriptblockchainterraform
   136 followers
   dismiss this company
 * AppLike Group - justDice, adjoe and Sunday
   Follow
   #GoBig #MoveFast #BeDirect #BeAppLike #HaveFun
   javascriptamazon-web-services
   3 open jobs · 14 followers
   dismiss this company


By selecting follow, you are opting in to receive an email digest from the
companies you follow. Don't worry, your information isn't shared.
More companies on Stack Overflow

43 people chatting
JavaScript
1 hour ago - Markus

Tamil iOS, Web and Phonegap Developers
4 hours ago - jafarbtech


LINKED

0
Chrome extension is storing the undefined value
72
How can I get the current tab URL for chrome extension?
8
chrome.tabs.getCurrent() or tabs.query()
2
Some variables are loaded multiple times
0
Getting current tab url after click
0
How to get active tab index on Google Chrome extension?
1
Get current tab url - Chrome Extension
-1
How can I create a window like the one in the image below in chrome extension?
0
Getting active tab information using chrome extension api
0
Access URL of Current Tab in chrome extension (scope problems)
See more linked questions

RELATED

5097
What's the best way to validate an email address in JavaScript?
7626
How do JavaScript closures work?
4409
How do you get a timestamp in JavaScript?
2661
Encode URL in JavaScript?
1971
Get current URL with jQuery?
5801
How do I include a JavaScript file in another JavaScript file?
3374
Get the current URL with JavaScript?
5008
How to replace all occurrences of a string in JavaScript
7418
How to check whether a string contains a substring in JavaScript?
4937
How to change the URI (URL) for a remote Git repository?

HOT NETWORK QUESTIONS

 * 
   Is it a good idea to make the actions of my antagonist reasonable?
 * 
   Is there a simple way to convert "{a,b,c}" to "a,b,c"?
 * 
   Why do we need insulation material between two walls?
 * 
   What is the meaning behind Proverbs 27:14 Loudly blessing a neighbor early in
   the morning, will be taken as a curse
 * 
   Does carbon fiber not have a fatigue life?
 * 
   Why doesn't the US Navy utilize seaplanes?
 * 
   How does this Norton "upgrade" scam work?
 * 
   Was this carbon fibre bicycle rim been destroyed by a parrot?
 * 
   How could my island-country mostly populated by massive humanoids subsist its
   inhabitants?
 * 
   Where do the symbols for the Spheres in Mage: the Ascension come from?
 * 
   How did Rashi know Ben-Temalion was a small shed?
 * 
   Is time spent on litigation recoverable as lost wages?
 * 
   Which amount of fuel is important - mass or volume?
 * 
   Where is it possible to observe the moon for 24 hours?
 * 
   Sci-fi story where people are reincarnated at hubs and a man wants to figure
   out what is happening
 * 
   Would a heavy fork cause problem when climbing?
 * 
   Who would have been the optimal partner of Alia according to the Bene
   Gesserit?
 * 
   Travel to USA with not-registered-citizen infant born to US Citizen father
 * 
   Why do we care about chirality?
 * 
   Is this image of Compressor aerodynamics right?
 * 
   What previous results match/compare to Alireza Firouzja's 3000+ performance
   in the European Team Championships?
 * 
   Cantilever brake is missing its mounting screws and washers, how do I replace
   them?
 * 
   Identify an unusual double-ended ball socket link part
 * 
   How to make a duel between knight with a greatsword and mage with a
   one-handed sword fair?

Question feed


SUBSCRIBE TO RSS

Question feed

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.



lang-js

STACK OVERFLOW

 * Questions
 * Jobs
 * Developer Jobs Directory
 * Salary Calculator
 * Help
 * Mobile
 * Disable Responsiveness

PRODUCTS

 * Teams
 * Talent
 * Advertising
 * Enterprise

COMPANY

 * About
 * Press
 * Work Here
 * Legal
 * Privacy Policy
 * Terms of Service
 * Contact Us
 * Cookie Settings
 * Cookie Policy

STACK EXCHANGE
NETWORK

 * Technology
 * Life & arts
 * Culture & recreation
 * Science
 * Professional
 * Business
 * API
 * Data

 * Blog
 * Facebook
 * Twitter
 * LinkedIn
 * Instagram

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under
cc by-sa. rev 2021.11.19.40795

Stack Overflow works best with JavaScript enabled

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on
your device and disclose information in accordance with our Cookie Policy.

Accept all cookies Customize settings