Chrome Extension - How to capture Scroll Position on open tabs

2.8k views Asked by At

I currently capture scroll location on a tab by running it in a content script (see below) and injecting JQuery.

Question How do I apply scroll capture to all tabs open not just the current tab I'm on? My try below works for just current tab.

Unsure how to iterate a for loop across all tabs since don't have access to chrome.tabs API in content script. Am I approaching this wrong by constantly tracking scroll capture and should use a background.js to call a content_script function only on a certain event?

Thanks!

manifest.json

{
"manifest_version": 2,
"name": "ScrollPosition",
"version": "1.0",
"background": {
"page": "background.html"
},
"content_scripts": [
{ "matches": ["http://*/*", "https://*/*"],
"js": ["jquery-1.11.1.min.js","content_script.js"]}
],
"browser_action": {
    "default_icon": {
        "19": "images/icon19.png",
        "38": "images/icon38.png"
    },
    "default_popup": "popup.html"
},
"permissions": [
    "tabs",
    "windows",
    "<all_urls>",
    "chrome://favicon/",
]
}

content_script.js

var scrollPosition = 0;

function scrollPos() {
  $(document).scroll(function(){
    scrollPosition = $(this).scrollTop();  
    console.log('your scroll position is: '+scrollPosition);
  });
};

window.addEventListener("load", scrollPos);
1

There are 1 answers

0
Siva Narayanan On

You can use the background script to iterate over all tabs and inject custom scripts. You can iterate over all tabs in the background page using chrome.tabs.query. You can inject a script into a tab using chrome.tabs.executeScript. Now, you'll just need to send a message to the background script from your content script and you should be good to go.