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

HTML周输入控件取值问题及Content Security Policy报错求助

Fixing Your Week Picker & CSP Issues in Chrome Extensions

Hey there! Let’s tackle your problems step by step—first that frustrating Content Security Policy (CSP) error, then getting the week value, calculating Julian dates, and filling your workday table.

1. Fixing the "Refused to execute inline event handler" CSP Error

Chrome Extensions have strict default CSP rules that block inline event handlers (like onclick="myFunction()") for security reasons. Here’s how to fix it:

Do This Instead of Inline Events

Remove any inline event attributes from your HTML, and use addEventListener in your popup.js file to bind events. This is the safest and recommended approach.

Example HTML (no inline events):

<input type="week" id="weekPicker">
<button id="fillTableBtn">Fill Workday Table</button>
<table id="workdayTable">
  <!-- Table rows will be added dynamically -->
</table>

Bind the click event in popup.js:

// Wait for the DOM to fully load before accessing elements
document.addEventListener('DOMContentLoaded', () => {
  const weekPicker = document.getElementById('weekPicker');
  const fillBtn = document.getElementById('fillTableBtn');
  
  fillBtn.addEventListener('click', () => {
    // Your logic to get week value, calculate dates, and fill the table goes here
  });
});

If you absolutely need inline events (which we don’t advise, as it weakens security), you can modify your extension’s manifest.json to allow unsafe inline scripts. But this is a last resort:

{
  "manifest_version": 3,
  "content_security_policy": {
    "extension_pages": "script-src 'self' 'unsafe-inline'; object-src 'self'"
  }
}

2. Getting the Week Value & Calculating Workday Julian Dates

Once the CSP error is fixed, let’s handle the week picker and date logic:

Step 1: Retrieve the Week Value

The <input type="week"> returns a value in the format YYYY-WWW (e.g., 2024-W08 for the 8th week of 2024). You can split this into the year and week number:

const weekValue = weekPicker.value;
if (!weekValue) {
  alert('Please select a week first!');
  return;
}

// Split into year and week number
const [yearStr, weekStr] = weekValue.split('-W');
const year = parseInt(yearStr, 10);
const weekNumber = parseInt(weekStr, 10);

Step 2: Get the 5 Workdays of the Selected Week

We’ll calculate the Monday to Friday of the selected ISO week (ISO weeks start on Monday). Here’s a helper function to do that:

function getWorkdaysForWeek(year, weekNumber) {
  // Calculate the first Monday of the year
  const firstDayOfYear = new Date(year, 0, 1);
  const dayOfWeek = firstDayOfYear.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
  
  // Days needed to reach the first Monday
  const daysToFirstMonday = dayOfWeek <= 1 ? (1 - dayOfWeek) : (8 - dayOfWeek);
  const firstMonday = new Date(firstDayOfYear);
  firstMonday.setDate(firstMonday.getDate() + daysToFirstMonday);
  
  // Calculate the Monday of the target week
  const targetWeekMonday = new Date(firstMonday);
  targetWeekMonday.setDate(targetWeekMonday.getDate() + (weekNumber - 1) * 7);
  
  // Generate Monday to Friday dates
  const workdays = [];
  for (let i = 0; i < 5; i++) {
    const workday = new Date(targetWeekMonday);
    workday.setDate(workday.getDate() + i);
    workdays.push(workday);
  }
  
  return workdays;
}

Step 3: Calculate Julian Dates

Here’s a function to convert a Date object to a Julian Day (integer value for the date):

function calculateJulianDay(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // Convert to 1-based month
  const day = date.getDate();
  
  const a = Math.floor((14 - month) / 12);
  const y = year + 4800 - a;
  const m = month + 12 * a - 3;
  
  const julianDay = day + Math.floor((153 * m + 2) / 5) + 365 * y + 
                    Math.floor(y / 4) - Math.floor(y / 100) + 
                    Math.floor(y / 400) - 32045;
  
  return julianDay;
}

Step 4: Fill the Table

Put it all together to populate your table with workdays and their Julian dates:

function fillWorkdayTable(table, workdays) {
  // Clear existing table content
  table.innerHTML = '';
  
  workdays.forEach(day => {
    const row = document.createElement('tr');
    
    // Date cell
    const dateCell = document.createElement('td');
    dateCell.textContent = day.toLocaleDateString();
    
    // Julian Day cell
    const julianCell = document.createElement('td');
    julianCell.textContent = calculateJulianDay(day);
    
    row.appendChild(dateCell);
    row.appendChild(julianCell);
    table.appendChild(row);
  });
}

Final Combined Logic in popup.js

document.addEventListener('DOMContentLoaded', () => {
  const weekPicker = document.getElementById('weekPicker');
  const fillBtn = document.getElementById('fillTableBtn');
  const table = document.getElementById('workdayTable');
  
  fillBtn.addEventListener('click', () => {
    const weekValue = weekPicker.value;
    if (!weekValue) {
      alert('Please select a week first!');
      return;
    }
    
    const [yearStr, weekStr] = weekValue.split('-W');
    const year = parseInt(yearStr, 10);
    const weekNumber = parseInt(weekStr, 10);
    
    const workdays = getWorkdaysForWeek(year, weekNumber);
    fillWorkdayTable(table, workdays);
  });
  
  // Helper functions go here: getWorkdaysForWeek, calculateJulianDay, fillWorkdayTable
});

Notes to Keep in Mind

  • ISO Week vs. Local Week: The code above uses ISO week rules (Monday start, week 1 is the first week with at least 4 days in the year). If your region uses a different week start (e.g., Sunday), adjust the getWorkdaysForWeek function accordingly.
  • Browser Compatibility: <input type="week"> is supported in most modern browsers, but double-check if your target users need to support older versions.

内容的提问来源于stack exchange,提问作者Richard Bernstein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:57:38