Friday, 7 October 2016

html - Chrome extension Javascript running only on icon click




I want my Chrome Extension to load Javascript once user visits a website. But currently, the Javascript is executed only when user click the extension icon and till the extension popup is open.



I saw the answer in this Chrome extension to load the script without clicking on icon question.



My manifest.json is:



{
"manifest_version": 2,

"name": "Javascript example",

"description": "Some description.",
"version": "1.1",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"storage"

],
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["popup.js"]
}
]
}



The popup.js is:



document.addEventListener('DOMContentLoaded', () => {

alert("Working");
});


popup.html is:







Getting Started Extension's Popup








The alert dialog is shown only when I click the extension icon (i.e. when popup.html is run), not when a page loads. I want the popup.js file to execute without user needing to click the extension icon. What am I missing?


Answer



Your manifest works, but run_at defaults to document_idle which means that DOMContentLoaded has already fired. This can be fixed by specifying run_at to document_start instead.



{
"manifest_version": 2,

"name": "Javascript example",
"description": "Some description.",

"version": "1.1",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},

"permissions": [
"activeTab",
"storage"

],
"content_scripts": [
{
"matches": ["*://*/*"],
"run_at": "document_start",
"js": ["popup.js"]
}
]
}



Source: https://developer.chrome.com/extensions/content_scripts


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...