我有以下文件

manifest.json

{
        "name": "Get Response URL",
        "version": "1.0",
        "manifest_version": 2,
        "name": "Test" ,
        "browser_action": {
        "icon":"icon.png"
        },
        "background": {
        "persistent": false,
        "scripts": ["background.js"]
         },
        "browser_action": {
        "default_icon": "icon.png"
      },
        "permissions":["https://myblog.com/*"] ,//Put All your URL here
        "manifest_version": 2
 }

background.js

chrome.browserAction.onClicked.addListener(function (tab) { //Fired when User Clicks ICON

    if (tab.url.indexOf("https://myblog.com/page1.html")==0) { // Inspect whether the place where user clicked matches with our list of URL
        chrome.tabs.executeScript(tab.id, {
            "file": "page2.js"
        }, function () { // Execute your code
            console.log("Script Executed .. "); // Notification on Completion
        });

    }
    else  if (tab.url.indexOf("https://myblog.com/page2.html")==0) { // Inspect whether the place where user clicked matches with our list of URL
        chrome.tabs.executeScript(tab.id, {
            "file": "page1.js"
        }, function () { // Execute your code
            console.log("Script Executed .. "); // Notification on Completion
        });
    }
});

Page1.html

<html>
<head>
<title>Page1</title>
</head>
<body>
<input type='button' name='submit' id='myBtn' value='click here to move to next page' onclick="document.location.href='page2.html';" />
</body>
</html>

page2.html

<html>
<head>
<title>Page2</title>
</head>
<body>
<input type="text" name="textBox" id="myText" />
</body>
</html>

以及两个 JavaScript 文件 page1.js page2

page1.js

var button=document.getElementById("myBtn");
button.click();

Page2.js

document.getElementById("myText").value="Text Box";

我开发了一个 Chrome 扩展程序。在第一页上,当我单击 Chrome 扩展程序图标时,该功能按照 https://myblog.com/page1 页面的 JavaScript 文件( page1.js )运行良好。

我在 page1.js 的帮助下在 https://myblog.com/page1 页面上所做的就是单击一个按钮移动到 https://myblog.com/page2 的第二个页面。现在我希望 page2.js 应该像脚本一样在页面 https://myblog.com/page2 上工作(page2.js),但它不起作用。

当我单击第 1 页上的扩展图标,然后再次单击第 2 页上的扩展图标时,脚本运行良好。

但我想扩展图标应该在第 1 页上点击而不是重复。

编辑了问题
  • 添加了 page1.html 和 page2.html
  • page1.js 和 page2.js

  • 是否有可能做同样的事情。
    如果是,我在哪里做错了?

    最佳答案

    这是您需要做的。
    您的代码块 chrome.browserAction.onClicked.addListener(function (tab) { 使 JS 函数仅在您单击图标时执行。这就是为什么您的第 1 页有效而第 2 页无效的原因。

    您希望 page2.js 在 Page2.html 打开后立即运行,对吗?因此更改您的 Page2.html 的编码。在 page2.html 本身中添加以下代码。
    document.addEventListener("DOMContentLoaded", function(event) {//Do work});
    这将做的是,一旦加载了 Page2.html,它就会执行 Javascript。尽管它适用于大多数浏览器,但对于 IE 8 及以下版本则不行。

    如果您也需要 IE 8 及以下版本,请尝试使用以下代码:

    <script type="text/JavaScript">
    function funtionToBeCalled(){
    // code that will be exected after dom ready
    }
    
    window.onload=funtionToBeCalled;
    </script>
    

    10-06 15:57