Reputation: 683
I am writing an extension for the Chrome browser where I want to add an event listener for the window resize event. My method is being executed for the window load event, but not being executed for the resize event.
Below is the code for my manifest.json file
{
"name": "A browser action",
"version": "1.0",
"background": { "scripts": ["background.js"] },
"permissions": [
"tabs", "http://*/*"
],
"manifest_version": 2
}
Below is the code for my background.js file.
var myExtension =
{
init: function()
{
// The event can be DOMContentLoaded, pageshow, pagehide, load or unload.
alert("ASHSIH");
window.addEventListener("resize", this.onmyPageResize, false);
},
onmyPageResize: function(aEvent)
{
alert("RESIZED");
}
}
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
myExtension.init();
},false);
Upvotes: 1
Views: 5392
Reputation: 353
For future readers of this question, the chrome.windows
API provides an onBoundsChanged
event:
onBoundsChanged (Since Chrome 86)
Fired when a window has been resized; this event is only dispatched when the new bounds are committed, and not for in-progress changes.
https://developer.chrome.com/extensions/windows#event-onBoundsChanged
This is how the event can be used: chrome.windows.onBoundsChanged.addListener( callback() )
(Make sure the manifest.json
file declares the tabs
permission)
{
"name": "My extension",
...
"permissions": ["tabs"],
...
}
Upvotes: 2
Reputation: 15045
Chrome-o-Tile is one example of an extension which listens resize in its content script.
In manifest.json:
"content_scripts": [
{
"js": ["contentscript.js"],
"run_at": "document_start",
"matches": [
"<all_urls>"
]
}
],
In contentscript.js:
'use strict';
var timeoutId = 0;
window.addEventListener('resize', function() {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(function() {
chrome.runtime.sendMessage({method: 'resize'});
timeoutId = 0;
}, 100);
}, false);
In background.js:
chrome.runtime.onMessage.addListener(function requested(request) {
if (request.method === 'resize') {
...
}
)};
There is also an open issue to implement chrome.windows.onResize event for Chrome extensions.
Upvotes: 5
Reputation: 4582
The background.js file cannot capture resize events in the browser. You would need to inject a content script for that.
Upvotes: 3
Reputation: 1280
You can use jQuery's bind()
function.. http://api.jquery.com/bind/
$(window).bind('resize', function () {
//do something here
});
Upvotes: 0