【问题标题】:Chrome Extension Help: Trigger variable CSS from popup.htmlChrome 扩展帮助:从 popup.html 触发变量 CSS
【发布时间】:2012-02-07 03:16:00
【问题描述】:

好的,我正在构建一个这样的扩展:

  • 有一个浏览器操作,它调用一个 popup.html,它有一个输入字段、一个提交按钮和一个调用 javascript 操作的链接
  • 一个 background.html 页面,通过 popup.html 接收输入值数据,然后使用它们将自定义 CSS 注入页面

我正在使用 localStorage 来存储输入数据以供将来使用。以下是我需要帮助的内容:

  1. 当点击 popup.html 中的按钮时,在 background.html(注入 CSS)中运行 javascript
  2. 将popup.html中输入字段的数据传递到background.html

我搜索了谷歌源代码,但实际上找不到任何东西。我不希望将 CSS 注入每个页面(我知道如何执行此操作)或单击浏览器操作图标时(我也知道如何执行此操作)。仅当用户将数据输入到 popup.html 并单击链接或按钮时,我才需要注入该 CSS。

更新: 我仍然无法做我需要做的事情。这是我的代码:

    <script type="text/javascript">

  var bgrSize = localStorage.getItem('gridSize');
function insert(){

  chrome.tabs.executeScript(null, {code:'body{ backgroundImage:   -webkit-linear-gradient(#eee 0.05em, transparent 0.05em); backgroundPosition: 100% 0 %; backgroundSize: 100% '+ bgrSize +';}'});
}
    </script>

在我的 background.html 页面上。下面是从 popup.html 页面触发的内容:

    function showGrid(){
 chrome.extension.getBackgroundPage().insert();
}

单击按钮时会触发“showGrid”函数。 gridSize 数据已经存储在 localStorage 中(我有一部分 popup.html 会更新以显示 localStorage 信息)。 我究竟做错了什么?我就是想不通。顺便说一句,manifest.json 包括我的 background.html

【问题讨论】:

    标签: javascript css google-chrome google-chrome-extension


    【解决方案1】:
    1. 在弹出窗口中使用chrome.extension.getBackgroundPage,然后在后台页面中执行适当的功能。使用insertCSSexecuteScript 注入数据
    2. 如果您想稍后使用,请通过函数参数或 localStorage 传递数据。

    正在恢复:

    // popup.html
    <script>
    window.onload = function(){
    document.getElementById('my-form').addEventListener('submit', function(){
        console.log('popup');
        chrome.extension.getBackgroundPage().insert({
            param: 'example',
            input: document.getElementById('my-input').value
        });
    });
    }
    </script>
    <form id="my-form">
        <input type="text" id="my-input"/>
        <input type="submit" />
    </form>
    
    // background.html
    function insert(data){
        console.log('inserting', data.input);
        chrome.tabs.insertCSS(null, {
            code: 'a { font-size: ' + data.input + 'px;}'
        }, function(){
            console.log('inserted');
        });
    }
    
    // manifest.js
    ...
    "permissions": ["tabs", "*://*/*"]
    

    此示例有效 - 我已手动检查过;)

    【讨论】:

    • 我仍然遇到问题。我在原始帖子中发布了我的代码。感谢您的帮助,我对此很陌生。此外,我尝试了 executeScript 和 insertCSS 的变体。行为没有改变。
    • 我的错误——我使用了“executeScript”函数而不是“insertCSS”——我已经更新了我的答案。
    • 谢谢,我最终无法使用您的答案。我不知道为什么,它只是没有工作(那是在你更新全功能示例之前)。我根据 Google 找到的示例重写了扩展,并从 popup.html 中运行了 executeScript。幸运的是,这个扩展足够简单和轻量级,它不需要任何特别的东西来工作! :)
    • 好的,对于额外的 cmets 感到抱歉,但我终于让一切正常了! :) 原来,我很笨,错误地创建了背景页面,因此,background.html 中的任何功能都不起作用。我几乎为此发疯-.-
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多