1

我创建了 chrome 扩展,当我单击扩展时它应该改变页面主体颜色,但我希望它在页面加载时完成,其中警报显示控件正在通过代码,它也不是调用函数。请帮助解决这个问题

----------manifest.json------------

{
  "name": "My Page changer",
  "description": "Make the current page red",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "Make this page blue"
  },
  "manifest_version": 2
}

------------------ 背景.js--------------------

debugger;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete') {
    debugger;
        alert('I am here too ');
        /*chrome.tabs.executeScript({
            code: 'document.body.style.backgroundColor="blue"'
            //code : 'doWhatYouWant()'
        });*/
        // Execute some script when the page is fully (DOM) ready
        chrome.tabs.executeScript(null, {code:"doWhatYouWant();"});
    }
});


function doWhatYouWant(){
    alert('I am inside doWhatYouWant');     
    document.body.style.backgroundColor="blue";
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  // No tabs or host permissions needed!
  alert('i am here');
  console.log('Turning ' + tab.url + ' red!');
  chrome.tabs.executeScript({
    code: 'document.body.style.backgroundColor="red"'
  });
});
4

2 回答 2

2

您的doWhatYouWant函数存在于您的背景页面中,因此您将无法从内容脚本中调用它。

如果您要运行的代码超过几行,请考虑将其放入扩展程序中的文件中,并在调用时使用InjectDetails参数file:中的字段。chrome.tabs.executeScript

此外,如果您希望它在每个页面上运行,您可以在清单中将其声明为内容脚本,而不是使用chrome.tabs.onUpdated侦听器。

于 2013-10-21T09:04:58.523 回答
0

谷歌内容脚本教程中有“王子”示例: https ://developer.chrome.com/extensions/content_scripts.html#pi 我在学习“google-extenioning”(?)时尝试过,它工作正常。祝你好运!

eidt - 呃,忘了,文件在这里

于 2013-10-21T16:41:03.370 回答