0

I want to click my extension's browser action, and then have an iframe load before scrolling. window.addeventlistener("load", scroll, false); seems to be the problem right now.

I know that content scripts will make window.addEventListener work, but the content script will also inject the script all the time, and I only want to scroll when the browser action icon is clicked.

I also know that removing the window.addeventlistener("load", scroll, false);can make the scroll work, but then that wouldn't wait until the iframe has loaded. Please help.

manifest.json

{
 "manifest_version": 2,

 "name": "scroll",
 "description": "scroll",
 "version": "1.0",

 "browser_action": {
   "default_icon": {
     }
 },

 "background": {
   "scripts" : ["background.js"],
   "persistent" : false
 },

 "permissions": [
   "tabs", "<all_urls>"
 ]
}

background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(null, {file: "scroll.js"});
});

scroll.js

window.addEventListener("load", scroll, false);

function scroll (evt) {
    window.scrollTo(0, 800);
}
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
A.C.
  • 3
  • 4
  • Is this related to your inquiry? http://stackoverflow.com/questions/14801349/ultra-simple-chrome-extension-doesnt-addeventlistener-to-button-onclick-event – Android Enthusiast May 03 '16 at 12:20
  • Side note: the only permission you need here is [`"activeTab"`](https://developer.chrome.com/extensions/activeTab). – Xan May 03 '16 at 12:39

1 Answers1

2

It may happen that your code executes too late (after the load event).

The logic should be:

  • Check if the page is already loaded
    • If yes, execute immediately
    • Otherwise, attach a listener

document.readyState fulfills the role:

function scroll(evt) {
  window.scrollTo(0, 800);
}

if (document.readyState === "complete") {
  scroll();
} else {
  window.addEventListener("load", scroll, false);
}
Xan
  • 74,770
  • 16
  • 179
  • 206