【问题标题】:Chrome Extension Passing Variable to dynamically executing scriptsChrome 扩展传递变量以动态执行脚本
【发布时间】:2012-09-28 10:38:37
【问题描述】:

我正在构建一个 chrome 扩展,它会打开一个 jquery 对话框并询问用户当前的网站。

这是我到目前为止所做的

background.html

<html>
    <head>
        <script>
            var tabUrl='';
            chrome.browserAction.onClicked.addListener(function(tab) {
                tabUrl=tab.url; //this varible i want to pass to popup.js

                chrome.tabs.executeScript(null, 
                {file:"jquery-ui.css", 
                    runAt:"document_start"}, 
                function() {  });
                chrome.tabs.executeScript(null, 
                {file:"jquery.js", 
                    runAt:"document_start"}, 
                function () {

                    chrome.tabs.executeScript(null, 
                    {file:"jquery-ui.min.js"}, 
                    function () {
                        chrome.tabs.executeScript(null, {file:"popup.js"}, function()       { 
                        });                    
                    });
                });
            });
        </script>
        <script ></script>
    </head>
</html>

popup.js

$(function() {
var myurl='http://localhost/addReview.php?url='+tabUrl;
var NewDialog = $('<div id="MenuDialog" ><iframe id="loader" frameborder="0" style="height:400px;width:100%" src="'+myurl+'"></iframe></div>');
NewDialog.dialog({
        modal: true,
        title: "Curate to WishCart",
        show: 'clip',
        hide: 'clip',
        width: '744'
});

});

我尝试了另一种方式,我将 popup.js 代码复制到 background.html,但扩展控制台显示以下错误。

  1. 未定义符号$

  2. Uncaught TypeError: Object [object Object] has no method 'dialog'

我想将 tabUrl 传递给 popup.js,这样我就可以加载 i-frame 并使用 iframe src 属性发送当前选项卡 url。

【问题讨论】:

  • 您的代码中是否包含 jQuery(和 jQueryUI)?我在任何地方都看不到它。
  • 您可以将 jQuery 和 jQueryUI(包括 CSS)作为普通的
  • 也许这种方法会更好地帮助你:blog.michael-forster.de/2009/08/…
  • yes 对话框已正确打开,这意味着我的 jquery.js 和 jqueryUi 正在加载 ....

标签: javascript jquery jquery-ui google-chrome-extension


【解决方案1】:

传递给chrome.tabs.executeScript 方法的脚本将作为Content Script 执行。这意味着,它将无法访问背景页面的上下文和其中定义的变量。

我不确定,但根据文档,您可以尝试使用以下方法:

chrome.tabs.executeScript(null, 
    {
        file: "popup.js", 
        code:"showDialog(" + tabUrl + ")"
    });

注意:根据上面的示例,showDialog 函数必须在 popup.js 文件中定义为全局函数。

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 2021-12-11
    • 2018-12-03
    相关资源
    最近更新 更多