How To Execute Scripts On Background Page Of A Chrome Extension

本秂侑毒 提交于 2019-12-13 03:06:21

问题


I am developing a Chrome extention. My manifest.json is:

"page_action": {
    "default_icon": {
        "19": "icons/icon19.png",
        "38": "icons/icon38.jpg"
    },
    "default_popup": "options.html"
},

In my extension I am trying to execute scripts which attempt to run/reach on actual web page:

// in options.html
chrome.tabs.executescript(null,{code:"alert('hello!');"}) ;

But Chrome extension debugger outputs this error:

Uncaught TypeError: Object #<Object> has no method 'executescript'

I want to reflect any changes on options to content_script or actual web page immidiately.

In page_action scope, how can I reach "chrome" object?


回答1:


For now try changing executescript to executeScript the capital 'S' is important.

executeScript and insertCSS are mostly used to inject a js or css file into a given tab rather than the raw code. They are used when you want to inject that code in very specific situations. In your code you don't specify an id for what tab to inject the code into, so it just injects it in the given context. If you use a chrome.tabs.query like with the message passing, you should be able to inject the code into the actual tab.

It seems that you are trying to affect some sort of change on a given tab when you change options in a popup from a Page Action I personally would recommend using jQuery to make the actual changes while using the message passing from the other question to send a message to the given tab. You could try doing it with programmatic injection of css or Javascript, but successive changes in the options might have undesirable results.

I don't know the exact details of what kinds of changes you are trying to make. If they are purely css then you could have one stylesheet injected into the page and just toggle a class on the things you want to change and have a class for each scenario. If you describe what you are trying to do in more detail I could give a more detailed suggestion.



来源:https://stackoverflow.com/questions/15102282/how-to-execute-scripts-on-background-page-of-a-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!