You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展Google登录后authorized.js无法执行问题求助

问题描述

我正在开发一款集成Google登录功能的Chrome扩展,目前已完成Google账号登录功能,实现逻辑如下:

  • 以popup.html作为初始页面,引入popup.js处理Google OAuth认证逻辑,页面初始显示“Waiting for Google Sign-In”;
  • 登录成功后,通过popup.js将authorized.html的内容设置为popup.html中对应元素的innerHTML,以此展示授权后界面。

遇到的问题:authorized.html中的静态内容(如“Welcome! You are now authorized.”和“Hit end”)能正常显示,但关联的authorized.js脚本完全没有执行——既不输出console.log内容,也不抛出任何错误。尝试添加DOMContentLoaded监听、抛出测试错误均无效,但将authorized.js直接移至popup.html中时,虽会出现错误但能正常执行。使用Chrome DevTools调试也看不到authorized.js的相关输出。

相关代码示例

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>Google OAuth Sign-In</title>
  <script src="popup.js"></script>
</head>
<body>
   <div id="Sign-In TempUI" class="content-body">Waiting for Google Sign-In</div>
</body>
</html>

popup.js

console.log('popup.js loaded');
document.addEventListener('DOMContentLoaded', function () {
    const NewGUI = document.getElementById('Sign-In TempUI');
  
    chrome.identity.getAuthToken({ interactive: true }, function (token) {
      if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError.message);
        return;
      }
      console.log('Token acquired:', token);
      loadAuthorizedUI(token);
    });

    function loadAuthorizedUI(token) {
        console.log('Debug:', token);
      fetch('authorized.html')
        .then(response => response.text())
        .then(html => {
          console.log('HTML content:', html);
          NewGUI.innerHTML = html;
        })
        .catch(error =>  console.error('Error fetching or processing HTML:', error));
    }
});

authorized.html

<!-- Page Displayed after recieving token from OAuthetication. Should display GUI for Email handling --> 
<!DOCTYPE html>
<html>
<head>
  <title>Authorized UI</title>
</head>
<body>
  <h1>Welcome! You are now authorized.</h1>
  <ul id="emailList"></ul>
  <script src="authorized.js"></script>
  <div>Hit end</div>
</body>
</html>

authorized.js

// throw new Error('This is a test error from authorized.js');
console.log('authorized.js loaded');

原因分析与解决办法

原因

当你通过innerHTML插入包含<script>标签的HTML内容时,Chrome浏览器出于安全机制,不会自动解析并执行这些脚本。innerHTML仅负责解析DOM结构并插入元素,不会处理脚本的加载、解析与执行流程——即使脚本标签被插入到DOM中,浏览器也不会触发它的加载逻辑。

解决办法

需要分离静态DOM内容与脚本逻辑,手动加载并执行authorized.js,具体步骤如下:

  1. 修改authorized.html:移除外层的html、head、body标签,只保留需要插入的核心内容(避免重复嵌套页面结构):
<h1>Welcome! You are now authorized.</h1>
<ul id="emailList"></ul>
<div>Hit end</div>
  1. 修改popup.js中的loadAuthorizedUI函数:在插入静态HTML后,手动创建<script>元素并添加到页面中,触发脚本的加载与执行:
function loadAuthorizedUI(token) {
    console.log('Debug:', token);
    fetch('authorized.html')
        .then(response => response.text())
        .then(html => {
            console.log('HTML content:', html);
            NewGUI.innerHTML = html;
            // 手动创建script标签加载authorized.js
            const authScript = document.createElement('script');
            authScript.src = 'authorized.js';
            // 可选:监听脚本加载完成事件,传递token等数据
            authScript.onload = () => {
                console.log('authorized.js加载完成');
                // 如果authorized.js中有初始化函数,可在此调用并传入token
                // 例如:initAuthorizedUI(token);
            };
            document.body.appendChild(authScript);
        })
        .catch(error => console.error('Error fetching or processing HTML:', error));
}
  1. (可选)优化authorized.js逻辑:如果脚本依赖授权后的token,可以在popup.js的authScript.onload回调中调用authorized.js暴露的函数并传递参数,避免全局变量依赖。

内容的提问来源于stack exchange,提问作者Chibuike S. Eze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:05:53