使用Chrome扩展名中的popup.html图标运行JavaScript



我想要的很简单。用户单击扩展名的图标,执行JS代码,显示一个提示框,要求两个值。但是我不知道如何正确地将JS与popup.html链接。到目前为止,只需单击图标即可打开弹出窗口,而无需运行JS代码。

popup.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="prompt.js"></script>
    </head>
    <body onload="promptBox()">
    </body>
</html>

提示。JS

function promptBox() {
    prompt('Choose File 1',A14nH);
    R1Gh7=prompt('Choose File 2',L3f7);
    if(L3f7&&R1Gh7) {
        Fr4Q='<frameset cols='*,*'>n<frame src=''+L3f7+''/>';
        Fr4Q+='<frame src=''+R1Gh7+''/>n';
        Fr4Q+='</frameset>';
        with(document) {
            write(Fr4Q);
            void(close())
        }
    }
    else{
       void(null)
    };
}

您无法在Chrome扩展中运行内联操件。
右键单击您的扩展图标,然后单击" Inspect弹出"。您会看到以下内容:

拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:" script-src'self'chrome'chrome-extension-resource:"。

您需要从身体中删除onload="promptBox()",然后将听众添加到prompt.js

function promptBox() {
  // ...
}
document.addEventListener('DOMContentLoaded', function() {
  promptBox();
});
chrome.browserAction.onClicked.addListener(promptBox);

对于我想做的事情(通过插入帧来操纵当前页面),事实证明内容脚本是关键字。

背景脚本在扩展图标上敲击了onclick操作,并触发了调用atmentbox函数的内容脚本。

subtest.json

{
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "permissions": [
        "tabs",
        "http://*/*",
        "https://*/*"
    ],
    "browser_action": {
        "default_title": "Dual View Split Screen", 
        "default_icon": "icon48x48.png"
    }   
}

背景.js

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

提示。JS

function promptBox() {
    windowLeft = prompt('Please choose your left window:', document.URL);
    windowRight = prompt('Please choose your right window:', document.URL);
    if(windowLeft && windowRight) {
        result='<frameset cols='*,*'>n<frame src=''+windowLeft+''/>';
        result+='<frame src=''+windowRight+''/>n';
        result+='</frameset>';
        with(document) {
            write(result);
            void(close())
        }
    }
    else{
       void(null)
    };
};
chrome.extension.onClicked.addListener(promptBox());

最新更新