Certain JS code not working in Chrome extension

Hi,

I am writing a simple extension to do the following:

When I open a web page, and then press a hotkey (Ctrl + Space), the page should scroll to a certain vertical position (500px).

Here is the code I currently have:

manifest.json

{
    "name": "Scroll",
    "description" : "Scroll.",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "scripts": ["script.js"],
        "persistent": false
    },
    "commands": {
        "scroll": {
            "suggested_key": {
                "default": "Ctrl+Space"
            },
            "description": "Scroll"
        }
    }
}

script.js

chrome.commands.onCommand.addListener(function (command) {
    if (command == "scroll") {
        alert("Test");
    }
});

When I test the above, it works.

chrome.commands.onCommand.addListener(function (command) {
    if (command == "scroll") {
        window.scrollTo(0, 500);
    }
});

When I test the above, it doesn’t work.

Any ideas why alert() is working but window.scrollTo() is not working?

Thanks.

A commented out alert doesn’t display an alert. Is it using an older version of the code?

Sorry if I was not clear. I mean, when I test alert() alone, it works. When I test window.scrollTo() alone, it doesn’t work. I edited the code in my question for clarification.

Well, the page will need to have a body with an overflow is one thing.

The command in itself is correct. Could you stick all the files you are working with into a zip folder and post it here. That’ll make it much easier for us to help you.

2 Likes

I tested it on various sites/pages, they all have vertical overflow, i.e. visible scrollbar.

I have just the two files, with the code I mentioned in my question. Still, I uploaded them if that will clarify it further.

chrome-extension-scroll.zip (823 Bytes)

Thanks.

Your actions are being carried out on the background page. You can see this by going to chrome://extensions/ then selecting “Scroll” > “Details” > “Inspect Views” > “Background page”. Try logging something to the console (instead of alerting). It’ll appear here.

If you want to run the script on a regular webpage, you have to use a content_script and declare this in the manifest:

{
  "name": "Scroll",
  "description" : "Scroll.",
  "version": "1.0",
  "manifest_version": 2,
  "background": { "scripts": ["script.js"]	 },
  "content_scripts": [{
    "matches": [ "*://*.sitepoint.com/*" ],
    "js": [ "main.js" ],
    "run_at": "document_idle"
  }],
  "commands": {
    "scroll": {
      "suggested_key": {
        "default": "Ctrl+Space"
      },
      "description": "Scroll"
    }
  }
}

Then you need to send a message from the background script to the content script like so:

// script.js
chrome.commands.onCommand.addListener(function (command) {
  if (command == "scroll") {
    chrome.tabs.query(
      {currentWindow: true, active: true}, 
      (tabs) => { chrome.tabs.sendMessage(tabs[0].id, { text: 'scroll' }); }
    )
  }
});

You can read all about messaging here: https://developer.chrome.com/extensions/messaging

And finally, create main.js in the same folder as the manifest file and the content script:

// main.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.text) {
    switch (msg.text) {
      case 'scroll':
        window.scrollTo(0, 500);
        break;
      default:
        sendResponse('');
    }
  }
});

Now, refresh the extension, visit www.sitepoint.com/anything (the JS Channel page, for example)and hit the Ctrl + Space combo and you will be scrolled down the page.

Attached, you can find the files. Let me know if you have any questions :slight_smile:

chrome-extension-scroll.zip (1.3 KB)

3 Likes

Thank you very much, it works perfectly now. Seems I will need to use content scripts together with background scripts to achieve this type of tasks. I had been checking Google’s documentation but to be honest, it feels a little confusing for a beginner.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.