Friday 15 February 2013

javascript - browser_action to trigger content_script failed -



javascript - browser_action to trigger content_script failed -

what want when click browser_action icon, webpage css, failed next code, not respond @ all. idea?

the manifest json file this

{ "manifest_version": 2, "name": "test", "description": "yada yada", "version": "1.0", "permissions": [ "https://*/*", "tabs" ], "icons": { "128" : "icon.png" }, "browser_action": { "default_icon": "icon.png" }, "content_scripts": [ { "matches": [ "http://*/*", "https://*/*" ], "js": ["jquery.js","request.js"], "run_at": "document_end" } ] }

and request.js here

chrome.browseraction.onclicked.addlistener(function (){ document.body.style.background = 'yellow'; });

from understand, want alter css of relevant pages using programmatic injection. manifest.json should include next permission:

"permissions": [ "activetab" ],

access chrome.* api restricted in content scripts

once have permissions set up, can inject javascript page calling tabs.executescript. inject css, utilize tabs.insertcss.

so want (injects javascript code):

chrome.browseraction.onclicked.addlistener(function(tab) { chrome.tabs.executescript({ code: 'document.body.style.backgroundcolor="yellow"' }); });

alternatively, utilize insertcss method described in docs on activetab so:

chrome.browseraction.onclicked.addlistener(function(tab) { chrome.tabs.insertcss(tab.id, { code: 'document.body.style.backgroundcolor="yellow"' }); });

again docs:

if content script's code should injected, register in extension manifest using content_scripts field, in next example-

"content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.css"], //mystyle.css gets injected relevant pages. "js": ["jquery.js", "myscript.js"] } ],

edit - should have explicitly stated earlier, documentation says content scripts cannot

use chrome.* apis, exception of: extension ( geturl , inincognitocontext , lasterror , onrequest , sendrequest )

so can't next in content script (i wonder how worked you):

chrome.browseraction.onclicked.addlistener(function callback)

that said, have access browseraction api in background page(s). require this:

manifest.json:

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

background.js:

chrome.browseraction.onclicked.addlistener(function(tab) { chrome.tabs.executescript({ code: 'document.body.style.backgroundcolor="yellow"' }); });

in essence utilize chrome.browseraction in background pages content scripts don't back upwards it. hope clarify point , should help problem sorted.

javascript google-chrome-extension

No comments:

Post a Comment