

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>javascript筆記 &#8211; Max的程式語言筆記</title>
	<atom:link href="https://stackoverflow.max-everyday.com/category/js/feed/" rel="self" type="application/rss+xml" />
	<link>https://stackoverflow.max-everyday.com</link>
	<description>我要當一個豬頭，快樂過每一天</description>
	<lastBuildDate>Fri, 23 Jan 2026 21:16:41 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://stackoverflow.max-everyday.com/wp-content/uploads/2017/02/max-stackoverflow-256.png</url>
	<title>javascript筆記 &#8211; Max的程式語言筆記</title>
	<link>https://stackoverflow.max-everyday.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>JavaScript 取得 Chrome 版本號</title>
		<link>https://stackoverflow.max-everyday.com/2026/01/javascript-chrome-browser-version/</link>
					<comments>https://stackoverflow.max-everyday.com/2026/01/javascript-chrome-browser-version/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 23 Jan 2026 21:16:40 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=7654</guid>

					<description><![CDATA[現在 Chrome 提供一個很方便的物件。就是 ...]]></description>
										<content:encoded><![CDATA[
<p>現在 Chrome 提供一個很方便的物件。就是 navigator.userAgentData。</p>



<p>不需要再自己去切字串，直接看裡面的 brands 陣列，就能找到版本號。</p>



<h2 class="wp-block-heading">傳統的字串解析</h2>



<p>以前只能讀取 navigator.userAgent。那是一大串很亂的文字。</p>



<p>裡面混雜了各種軟體資訊，必須用正規表達式去找 Chrome 這個字，再把後面的數字拿出來，雖然麻煩但是支援度最高。</p>



<h2 class="wp-block-heading">程式實作範例</h2>



<p>先嘗試用新版 API 抓取，如果瀏覽器不支援就改用舊方法。這樣寫可以兼顧準確度跟相容性。</p>



<pre class="wp-block-code"><code>async function getChromeVersion() {
  // 優先使用現代 API
  if (navigator.userAgentData) {
    const brands = navigator.userAgentData.brands;
    const chrome = brands.find(b =&gt; b.brand === 'Google Chrome');
    if (chrome) return chrome.version;
  }

  // 備用的字串解析法
  const raw = navigator.userAgent.match(/Chrome\/(&#91;0-9.]+)/);
  return raw ? raw&#91;1] : '無法辨識';
}

// 執行並印出結果
getChromeVersion().then(version =&gt; {
  console.log('版本號是：' + version);
});
</code></pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2026/01/javascript-chrome-browser-version/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>chrome extension 是否可以自動點擊網頁彈出的 alert?</title>
		<link>https://stackoverflow.max-everyday.com/2025/03/disable-javascript-alert/</link>
					<comments>https://stackoverflow.max-everyday.com/2025/03/disable-javascript-alert/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 06 Mar 2025 08:13:37 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6542</guid>

					<description><![CDATA[Chrome Extension 無法直接自動點...]]></description>
										<content:encoded><![CDATA[
<p>Chrome Extension 無法直接自動點擊 <code>alert()</code>、<code>confirm()</code> 或 <code>prompt()</code> 這類 JavaScript 彈出視窗，因為這些是 <strong>瀏覽器模態對話框</strong>，會阻塞 JavaScript 的執行，且受安全性限制，擴充功能無法直接控制它們。</p>



<p>不過，你可以用 <strong>以下方式間接處理</strong>：</p>



<h3 class="wp-block-heading">1&#x20e3; <strong>攔截 <code>window.alert</code> 讓它自動關閉</strong></h3>



<p>擴充功能的內容腳本（Content Script）可以覆蓋 <code>window.alert</code>，讓它變成一個無作用的函數，這樣網頁上的 <code>alert()</code> 就不會真正彈出：</p>



<pre class="wp-block-code"><code>// 在 content script 中執行
window.alert = function() {};
window.confirm = function() { return true; }; // 自動按「確定」
window.prompt = function() { return null; };  // 自動點「取消」
</code></pre>



<h3 class="wp-block-heading">2&#x20e3; <strong>使用 <code>debugger</code> Protocol 遠端控制 alert</strong></h3>



<p>如果你希望擴充功能能夠真的 <strong>自動點擊</strong> <code>alert()</code>，你可以使用 <strong>Chrome DevTools Protocol</strong> (CDP)，透過 <code>chrome.debugger</code> 來攔截並關閉對話框（需要 <code>debugger</code> 權限）。</p>



<h4 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f680.png" alt="🚀" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>示例：用 <code>chrome.debugger</code> 關閉 alert</strong></h4>



<p>在擴充功能的背景程式 (<code>background.js</code>) 中：</p>



<pre class="wp-block-code"><code>chrome.debugger.attach({ tabId: YOUR_TAB_ID }, "1.3", function() {
    chrome.debugger.sendCommand({ tabId: YOUR_TAB_ID }, "Page.handleJavaScriptDialog", {
        accept: true // 自動按「確定」
    });
});
</code></pre>



<p>這樣就能讓擴充功能在偵測到 alert 彈出時，直接「按下」確定。</p>



<h3 class="wp-block-heading">3&#x20e3; <strong>模擬使用者按鍵（僅適用於特定場景）</strong></h3>



<p>如果 <code>alert()</code> 已經彈出，而你的擴充功能沒有 <code>debugger</code> 權限，可以嘗試 <strong>模擬鍵盤按鍵</strong>（例如 <code>Enter</code>）來關閉對話框：</p>



<pre class="wp-block-code"><code>document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));
</code></pre>



<p>不過，這種方式 <strong>不一定有效</strong>，因為瀏覽器的 alert 是模態對話框，可能無法被 JavaScript 操作。</p>



<h3 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>結論</strong></h3>



<ul class="wp-block-list">
<li><strong>最佳解法：</strong> 用 <code>window.alert = function() {};</code> 來攔截 <code>alert()</code>，讓它不彈出。</li>



<li><strong>進階解法：</strong> 如果你的擴充功能有 <code>debugger</code> 權限，可以用 <code>chrome.debugger</code> 來自動按「確定」。</li>



<li><strong>可行但不穩定：</strong> 嘗試模擬 <code>Enter</code> 鍵來關閉 alert（視瀏覽器行為而定）。</li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2025/03/disable-javascript-alert/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>chrome extension &#8220;manifest_version&#8221;: 3 , 使用 chrome.declarativeNetRequest.updateDynamicRules(roles,function(){}); 來阻止瀏覽器下載特定網址</title>
		<link>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/</link>
					<comments>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 21 Feb 2025 10:44:14 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6346</guid>

					<description><![CDATA[希望可以擋掉這個 url: https://te...]]></description>
										<content:encoded><![CDATA[
<p>希望可以擋掉這個 url: https://test.sg/js/ads.js?v=20241127200620, 在 rule.condition.urlFilter = &#8220;*test.sg/js/ads.* 但是實際瀏覽網頁, 檔案還是被瀏覽器下載</p>



<p>您好，針對您在使用 Chrome 擴充功能 <code>chrome.declarativeNetRequest.updateDynamicRules</code> 嘗試阻擋特定網址 <code>https://test.sg/js/ads.js?v=20241127200620</code> 時遇到的問題，以下是一些可能的解決方案和注意事項：</p>



<p><strong>1. 精確匹配 URL：</strong></p>



<ul class="wp-block-list">
<li>您的 <code>rule.condition.urlFilter = "*test.sg/js/ads.*"</code> 可能過於寬鬆。由於 URL 中包含查詢參數 <code>?v=20241127200620</code>，因此僅使用 <code>*test.sg/js/ads.*</code> 可能無法完全匹配。</li>



<li>嘗試使用更精確的匹配模式，例如：
<ul class="wp-block-list">
<li><code>rule.condition.urlFilter = "test.sg/js/ads.js?v=20241127200620"</code> (完全匹配)</li>



<li><code>rule.condition.urlFilter = "test.sg/js/ads.js"</code> (匹配不帶查詢參數的版本)</li>



<li><code>rule.condition.urlFilter = "test.sg/js/ads*"</code> (匹配任何以ads開頭的資源)</li>
</ul>
</li>



<li>如果查詢參數的值會變動，您可以使用更複雜的匹配模式，例如正規表達式。</li>
</ul>



<p><strong>2. 使用正規表達式：</strong></p>



<ul class="wp-block-list">
<li><code>declarativeNetRequest</code> 支援使用正規表達式進行更靈活的 URL 匹配。</li>



<li>您可以嘗試使用以下正規表達式：
<ul class="wp-block-list">
<li><code>rule.condition.regexFilter = "test\\.sg\\/js\\/ads\\.js\\?v=.*"</code></li>



<li>請注意，在正規表達式中，特殊字元（如 <code>.</code> 和 <code>?</code>）需要進行轉義。</li>
</ul>
</li>
</ul>



<p><strong>3. 檢查規則的優先順序：</strong></p>



<ul class="wp-block-list">
<li>如果您的擴充功能中有多個 <code>declarativeNetRequest</code> 規則，請確保您的阻擋規則具有足夠高的優先順序。</li>



<li><code>rule.priority</code> 屬性用於設定規則的優先順序，數值越小，優先順序越高。</li>
</ul>



<p><strong>4. 檢查規則的動作類型：</strong></p>



<ul class="wp-block-list">
<li>確保您的規則的 <code>rule.action.type</code> 屬性設定為 <code>"block"</code>，以阻止請求。</li>
</ul>



<p><strong>5. 檢查擴充功能的權限：</strong></p>



<ul class="wp-block-list">
<li>確保您的擴充功能在 <code>manifest.json</code> 檔案中具有足夠的權限。</li>



<li>您需要 <code>declarativeNetRequest</code> 和 <code>declarativeNetRequestWithHostAccess</code> 權限，以及對目標網域的 host permissions。</li>



<li>範例: JSON<code>"permissions": [ "declarativeNetRequest", "declarativeNetRequestWithHostAccess" ], "host_permissions": [ "*://*.test.sg/*" ]</code></li>
</ul>



<p><strong>6. 檢查 Chrome 版本：</strong></p>



<ul class="wp-block-list">
<li><code>declarativeNetRequest</code> API 在 Chrome 84 及更高版本中可用。</li>



<li>確保您的 Chrome 瀏覽器版本足夠新。</li>
</ul>



<p><strong>7. 偵錯方法：</strong></p>



<ul class="wp-block-list">
<li>使用 Chrome 的開發人員工具（DevTools）的 &#8220;Network&#8221; 標籤來檢查網路請求，確認 <code>ads.js</code> 檔案是否被下載，以及請求的詳細資訊。</li>



<li>您可以使用 <code>chrome.declarativeNetRequest.getDynamicRules</code> 來檢查您的擴充功能是否成功新增了規則。</li>



<li>您可以使用chrome://net-export/來紀錄網路事件，以方便除錯。</li>
</ul>



<p><strong>範例程式碼：</strong></p>



<p>JavaScript</p>



<pre class="wp-block-code"><code>chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: &#91;1], // 移除現有規則（如果存在）
  addRules: &#91;{
    "id": 1,
    "priority": 1,
    "action": { "type": "block" },
    "condition": {
      "urlFilter": "test.sg/js/ads.js?v=20241127200620",
      "resourceTypes": &#91;"script"] // 只阻擋腳本
    }
  }]
}, function() {
  console.log("規則已更新");
});
</code></pre>



<p>請根據您的實際情況調整程式碼，並仔細檢查您的擴充功能權限和 Chrome 版本。希望這些資訊能幫助您解決問題。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>以上面的範例, 修改成阻止下列的url: </p>



<pre class="wp-block-code"><code>&#91;"*.doubleclick.net/*",
"*.ssp.hinet.net/*",
"*a.amnet.tw/*",
"*adx.c.appier.net/*",
"*cdn.cookielaw.org/*",
"*clarity.ms/*"]</code></pre>



<p>好的，以下是如何修改範例程式碼，以阻擋您提供的 URL 列表：</p>



<p><strong>1. 修改 <code>manifest.json</code>：</strong></p>



<p>首先，確保您的 <code>manifest.json</code> 檔案中有足夠的權限：</p>



<p>JSON</p>



<pre class="wp-block-code"><code>{
  "manifest_version": 3,
  "name": "URL Blocker",
  "version": "1.0",
  "permissions": &#91;
    "declarativeNetRequest",
    "declarativeNetRequestWithHostAccess"
  ],
  "host_permissions": &#91;
    "*://*.doubleclick.net/*",
    "*://*.ssp.hinet.net/*",
    "*://*.amnet.tw/*",
    "*://*.adx.c.appier.net/*",
    "*://*.cdn.cookielaw.org/*",
    "*://*.clarity.ms/*"
  ],
  "background": {
    "service_worker": "background.js"
  }
}
</code></pre>



<p><strong>2. 修改 <code>background.js</code>：</strong></p>



<p>然後，修改 <code>background.js</code> 檔案，以新增多個規則：</p>



<p>JavaScript</p>



<pre class="wp-block-code"><code>const urlsToBlock = &#91;
  "*.doubleclick.net/*",
  "*.ssp.hinet.net/*",
  "*a.amnet.tw/*",
  "*adx.c.appier.net/*",
  "*cdn.cookielaw.org/*",
  "*clarity.ms/*"
];

const rules = urlsToBlock.map((url, index) =&gt; ({
  "id": index + 1,
  "priority": 1,
  "action": { "type": "block" },
  "condition": {
    "urlFilter": url,
    "resourceTypes": &#91;"main_frame", "sub_frame", "script", "image", "stylesheet", "object", "xmlhttprequest", "other"] // 阻擋所有資源類型
  }
}));

chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: rules.map(rule =&gt; rule.id), // 移除現有規則
  addRules: rules
}, function() {
  console.log("規則已更新");
});
</code></pre>



<p><strong>程式碼說明：</strong></p>



<ul class="wp-block-list">
<li><strong><code>urlsToBlock</code> 陣列：</strong> 包含了您要阻擋的 URL 列表。</li>



<li><strong><code>rules</code> 陣列：</strong> 使用 <code>map</code> 函式將 URL 列表轉換為 <code>declarativeNetRequest</code> 規則陣列。
<ul class="wp-block-list">
<li>每個規則都有一個唯一的 <code>id</code>（從 1 開始）。</li>



<li><code>priority</code> 設定為 1，表示高優先順序。</li>



<li><code>action.type</code> 設定為 <code>"block"</code>，表示阻擋請求。</li>



<li><code>condition.urlFilter</code> 設定為要阻擋的 URL。</li>



<li><code>resourceTypes</code> 設定為阻擋所有資源類型，可以依據需求進行調整。</li>
</ul>
</li>



<li><strong><code>chrome.declarativeNetRequest.updateDynamicRules</code>：</strong>
<ul class="wp-block-list">
<li><code>removeRuleIds</code> 移除所有現有規則。</li>



<li><code>addRules</code> 新增 <code>rules</code> 陣列中的規則。</li>
</ul>
</li>
</ul>



<p><strong>注意事項：</strong></p>



<ul class="wp-block-list">
<li>請確保您的 Chrome 瀏覽器版本支援 <code>declarativeNetRequest</code> API。</li>



<li>擴充功能權限非常重要，請仔細檢查 <code>manifest.json</code> 中的 <code>permissions</code> 和 <code>host_permissions</code>。</li>



<li>您可以使用 Chrome 開發人員工具的 &#8220;Network&#8221; 標籤來驗證 URL 是否被成功阻擋。</li>



<li>resourceTypes可以依據需求調整，例如只阻擋script檔案，可以將resourceTypes設定為[&#8220;script&#8221;].</li>
</ul>



<p>希望這些資訊對您有幫助。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2025/02/chrome-extension-manifest_version-3-block-url-fail/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to display Base64 images in HTML</title>
		<link>https://stackoverflow.max-everyday.com/2024/12/how-to-display-base64-images-in-html/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/12/how-to-display-base64-images-in-html/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Tue, 31 Dec 2024 13:51:31 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6047</guid>

					<description><![CDATA[因為有些網站把驗證碼放在 shadow root...]]></description>
										<content:encoded><![CDATA[
<p>因為有些網站把驗證碼放在 shadow root 裡, 在取出資料後, 希望在 dom 裡產生出相同內容的圖片, </p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="802" height="296" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/12/2024-12-31_21-51_4q.jpg?v=1735653089" alt="" class="wp-image-6048" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/12/2024-12-31_21-51_4q.jpg?v=1735653089 802w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/12/2024-12-31_21-51_4q-600x221.jpg?v=1735653089 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/12/2024-12-31_21-51_4q-768x283.jpg?v=1735653089 768w" sizes="(max-width: 802px) 100vw, 802px" /></figure>



<p>base 64 字串放產生成圖片:</p>



<pre class="wp-block-code"><code>How to display Base64 images in HTML</code></pre>



<p>var img = document.createElement(&#8220;img&#8221;);<br>img.classList.add(&#8216;image_class&#8217;);<br>img.style = &#8220;vertical-align: middle; border-style: none; width: 170px; height: 50px;&#8221;;<br>img.src = &#8220;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZCAYAAACxZDnAAAAAAXNSR0IArs4c6QAAA6dJREFUaEPlmc9rE0EUx7/zD/gTwYu44KFiI1bqySKYUxMR8SBWmouYpXootIfk0kLFQgVJDhY8SNlAPaRYqeBB3ApCAtqTVFrYiAXBXXOxJ8WD19XdzObH/pzdnaZt3FsyO2/e+8x333uzS3Rd19HDFyEEeyFEEhf0Un8/Rmu1Ht4qPqFFBj3/cx4ThyccXhAC7PYzshd8sIOJDNowZMA2LjfgfjpQFMUcTiQSfOTC0crC4DrG1gc5WmyYigS6+ooguen0JXdLR6HP3UcLrh1wh/rqZbwZnsMv888RXPo8gxMxQq7mgWSxZSBXAQqXIxjUSkgLIlZdp6YgqTKyJ/3tRgeNCvTrLa8NdU8emWwWnnawLOr9Xc7g9cMNCAs1XBwC7L8dj+KDf0XuvncdtyBXdMD0sgqQJBAZthtHcwNWcGMnQT86pkIe6txGL9UGaUirl1EbngOm3+JKpqXh+uwZvN+axp8vpyGGeZw1IC0AkAA521q9lAbEBKAXgjxiG6/mCZKKBFXOIkDQUVKHhtJTAStnG6Dd4LLmbo3G4+Wkqeq5Ps8UErbocQVN00miojOlI+bU0QpKw+xjAd8O3sbi90WKKgVpXEb2aKcSvDqTIMANK3XUMsPYxDSuljM4wCYy77to6pBUBOZTlqW0UhqCmEBFLzRSU8DFBLoz337Es5d3UDzXlqO38iDPi/ArhpYfBuTAx8yohR9msTS2jENTqx3pxC0e30MJBWzM88vPN8cH8OLJRhAvOl5FniShSCrkoCpIZ3iCDptvzU7EViDbvWZTMZ2x1oCMgSk+aqZm8wQo5jjk6GoeJKkwdRsWAwfoqD2uCfqHBPWeszC4qZh4dA1Wt8Ebshkwl/ShoZQWIG6fgv7pK+MTEKWPNtOEYsvJjQIpHu9s+UKp2MjKRpexTLgruUkjRovXfNVgqrmIHGMR9FR08BY5oWpraQjv0IQfFrCxZlPJIwsYnRkKdsPvDg+gWgkQRCBOQQzT0rW7yFQMnTFR2NvWSKvrYCl2DnvWifA8pw4DgNnKAVBlWnxpb70aJ0fTls7YKdYiGEPR8cTmNrupZrfBGEdx+xE8ZTvAhI3EVHMxx9zScVB0WBdj3B/2VOLe/+36K8WIqSMGuP90KnfQPATYi3vBHXS3IO3Ul52dsrtvQXdrQ8Ou43WU35eg98oH1zCbsC9BhwnQ7V7jc9Xdaxd8PxzEXcM+PxJor/cUvJ3rpj2Wb4Vx4o4EupsAemWtv0PJ5MUsKZx0AAAAAElFTkSuQmCC&#8221;;<br>document.body.appendChild(img);</p>



<p></p>



<p>微調上面的程式, 避免重覆 append element 到 dom, 使用到的 javascript, 包住 javascript 的是 python script:</p>



<pre class="wp-block-code"><code>js = """
var img = document.querySelector("img.image_class");
var do_append = false; 
if (!img) {{img = document.createElement("img");do_append = true;}}
img = document.createElement("img");
img.classList.add('image_class');
img.style = "vertical-align: middle; border-style: none; width: 170px; height: 50px;";
img.src = '{}';
if (do_append) document.body.appendChild(img);""".format(img_data)</code></pre>



<p></p>



<p>img 取出為 image data:</p>



<pre class="wp-block-code"><code>let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
context.drawImage(img, 0, 0);
let img_data = canvas.toDataURL();
if(img_data) {image_data = img_data.split(",")&#91;1];}
return img_data;</code></pre>



<p></p>



<p>除了把 img 放回 dom 的解法, 也可以直接把 image data 進行 ocr, pythone sample code:</p>



<pre class="wp-block-code"><code>ocr_answer = ""
img_base64 = None
if len(img_data) &gt; 0:
    img_base64 = base64.b64decode(img_data.split(',')&#91;1])
if img_base64:
    ocr_answer = ocr.classification(img_base64)
if len(ocr_answer) == 4:
    # 輸入答案到輸入框.
    pass
else:
    # 點擊畫面上重新產生驗證碼.
    pass</code></pre>



<p></p>



<p>自動化之後的預覽:<br><a href="https://www.youtube.com/shorts/vUGt2ComgRY">https://www.youtube.com/shorts/vUGt2ComgRY</a></p>



<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="Screen Recording 2025 01 01" width="640" height="360" src="https://www.youtube.com/embed/vUGt2ComgRY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">資料來源</h2>



<p>How to display base64 encoded image in html<br><a href="https://stackoverflow.com/questions/41053901/how-to-display-base64-encoded-image-in-html">https://stackoverflow.com/questions/41053901/how-to-display-base64-encoded-image-in-html</a></p>



<p>How to display Base64 images in HTML<br><a href="https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html">https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/12/how-to-display-base64-images-in-html/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>jquery-smartwizard</title>
		<link>https://stackoverflow.max-everyday.com/2024/11/jquery-smartwizard/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/11/jquery-smartwizard/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 22 Nov 2024 06:44:12 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6031</guid>

					<description><![CDATA[有好心人分享 wizard 的元件，使用起來還滿...]]></description>
										<content:encoded><![CDATA[
<p>有好心人分享 wizard 的元件，使用起來還滿簡單的，github 專案：<br><a href="https://github.com/techlab/jquery-smartwizard">https://github.com/techlab/jquery-smartwizard</a></p>



<p>執行截圖：</p>



<figure class="wp-block-image size-full"><img decoding="async" width="900" height="785" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Screenshot-2024-11-22-at-2.23.52 PM.png?v=1732256760" alt="" class="wp-image-6032" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Screenshot-2024-11-22-at-2.23.52 PM.png?v=1732256760 900w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Screenshot-2024-11-22-at-2.23.52 PM-600x523.png?v=1732256760 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Screenshot-2024-11-22-at-2.23.52 PM-768x670.png?v=1732256760 768w" sizes="(max-width: 900px) 100vw, 900px" /></figure>



<p></p>



<p>簡單的範例：<br><a href="https://codepen.io/techlab/pen/JjGZvaz">https://codepen.io/techlab/pen/JjGZvaz</a></p>



<p>html:</p>



<pre class="wp-block-code"><code>&lt;div id="smartwizard">
    &lt;ul class="nav">
       &lt;li>
           &lt;a class="nav-link" href="#step-1">
              Step 1
           &lt;/a>
       &lt;/li>
       &lt;li>
           &lt;a class="nav-link" href="#step-2">
              Step 2
           &lt;/a>
       &lt;/li>
       &lt;li>
           &lt;a class="nav-link" href="#step-3">
              Step 3
           &lt;/a>
       &lt;/li>
       &lt;li>
           &lt;a class="nav-link" href="#step-4">
              Step 4
           &lt;/a>
       &lt;/li>
    &lt;/ul>
 
    &lt;div class="tab-content">
       &lt;div id="step-1" class="tab-pane" role="tabpanel">
          Step 1 content
       &lt;/div>
       &lt;div id="step-2" class="tab-pane" role="tabpanel">
          Step 2 content
       &lt;/div>
       &lt;div id="step-3" class="tab-pane" role="tabpanel">
          Step 3 content
       &lt;/div>
       &lt;div id="step-4" class="tab-pane" role="tabpanel">
          Step 4 content
       &lt;/div>
    &lt;/div>
&lt;/div></code></pre>



<p>說明：&lt;div class=&#8221;tab-content&#8221;> 必須存在，不然程式會出錯。</p>



<p>範例2:<br><a href="https://techlaboratory.net/jquery-smartwizard">https://techlaboratory.net/jquery-smartwizard</a></p>



<p>下一步：</p>



<pre class="wp-block-code"><code>$('#smartwizard').smartWizard("next");</code></pre>



<p>上一步：</p>



<pre class="wp-block-code"><code>$('#smartwizard').smartWizard("prev");</code></pre>



<p>重設：</p>



<pre class="wp-block-code"><code>$('#smartwizard').smartWizard("reset");</code></pre>



<p>到指定 step: // Go to step without force</p>



<pre class="wp-block-code"><code>$('#smartwizard').smartWizard("goToStep", 3);</code></pre>



<p>到指定 step: // Go to step with force</p>



<pre class="wp-block-code"><code>$('#smartwizard').smartWizard("goToStep", 3, true);</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/11/jquery-smartwizard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>d3js 圖表增加邊框</title>
		<link>https://stackoverflow.max-everyday.com/2024/11/d3js-chart-border-color-size/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/11/d3js-chart-border-color-size/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 08 Nov 2024 09:06:59 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6014</guid>

					<description><![CDATA[原來增加邊框只要設屬性就可以了，而且效果是可以套...]]></description>
										<content:encoded><![CDATA[
<p>原來增加邊框只要設屬性就可以了，而且效果是可以套到 svg 格式裡，不是只有網頁 css 上的效果。</p>



<p>效果圖：</p>



<figure class="wp-block-image size-full"><img decoding="async" width="700" height="500" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart.png?v=1731056605" alt="" class="wp-image-6015" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart.png?v=1731056605 700w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-600x429.png?v=1731056605 600w" sizes="(max-width: 700px) 100vw, 700px" /></figure>



<p>上面程式碼：</p>



<pre class="wp-block-code"><code>.attr("stroke", "black")
.style("stroke-width", "2px")</code></pre>



<ul class="wp-block-list">
<li>border color 使用 stroke attribute, 可以使用 #開頭的色碼。</li>



<li>border size 使用 stroke-width attribute.</li>
</ul>



<p></p>



<p>資料來源：<a href="https://d3-graph-gallery.com/graph/pie_basic.html">https://d3-graph-gallery.com/graph/pie_basic.html</a></p>



<p>完整程式碼：</p>



<pre class="wp-block-code"><code>svg
.selectAll('whatever')
.data(data_ready)
.enter()
.append('path')
.attr('d', d3.arc()
.innerRadius(0)
.outerRadius(radius)
)
.attr('fill', function(d){ return(color(d.data.key)) })
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7)</code></pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/11/d3js-chart-border-color-size/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Javascript: Check for an array of keywords match in a string</title>
		<link>https://stackoverflow.max-everyday.com/2024/11/javascript-check-for-an-array-of-keywords-match-in-a-string/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/11/javascript-check-for-an-array-of-keywords-match-in-a-string/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 06 Nov 2024 03:32:11 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6008</guid>

					<description><![CDATA[檢查某字串必須符合陣列中某一關鍵字。 範例1 R...]]></description>
										<content:encoded><![CDATA[
<p>檢查某字串必須符合陣列中某一關鍵字。</p>



<p>範例1 RegExp： or logic</p>



<pre class="wp-block-code"><code>const animals = &#91;"dog", "fish", "bird", "cat"];
const regex = new RegExp(animals.join("|")) // animals seperated by a pipe "|"

if (regex.test("I love cats")) {
  console.log("Yes");
}

// if you don't want to create an array then:
if (/dog|fish|bird|cat/.test("I love elephants")) {
  console.log("Yes");
}</code></pre>



<p></p>



<p>範例2 RegExp： and logic</p>



<pre class="wp-block-code"><code>function buildRegEx(str, keywords){
  return new RegExp("(?=.*?\\b" + 
    keywords
      .split(" ")
      .join(")(?=.*?\\b") +                     
    ").*", 
    "i"
  );
}

function test(str, keywords, expected){
  var result = buildRegEx(str, keywords).test(str) === expected
  console.log(result ? "Passed" : "Failed");
}

// Same order and have all keywords 
test("Hello world!", "hello world", true);
// Same order and have all keywords 
test("Hello all in the world!", "hello world", true);
// Any order but have all keywords 
test("Hello world!", "world hello", true);
// Same order and all keywords 
test("Hello world!", "worl hell", true);
// Have all keywords in any order 
test("Hello world!", "world", true);
// No contains all keywords 
test("Hello world!", "where you go", false);
// No contains all keywords
test("Hello world!", "z", false);
// No contains all keywords 
test("Hello world!", "z1 z2 z3", false);
// Contains all keywords in any order 
test("Hello world!", "wo", true);</code></pre>



<p></p>



<p>RegExp 比較難理解一點，下面 indexOf 就簡單一點點：</p>



<pre class="wp-block-code"><code>const keyword_array = area_keyword.split(" ");
let contain = true;
for(var j = 0; j &lt; keyword_array.length; j++){
    if(keyword_array&#91;j] == "") continue;
    if (html_text.indexOf(keyword_array&#91;j]) == -1) {
        contain = false
        break;
    }
}                    
if (contain) {
    // bingo~
}</code></pre>



<p></p>



<p></p>



<p>RegExp 常見用法：</p>



<ul class="wp-block-list">
<li>\ 反斜線放在非特殊符號前面，使非特殊符號不會被逐字譯出，代表特殊作用。 例如：&#8217;b&#8217; 如果沒有 &#8216;\&#8217; 在前頭，功能是找出小寫 b；若改為 &#8216;\b&#8217; 則代表的是邊界功能，block 用意。 /\bter\b/.test(&#8220;interest&#8221;) //false /\bter\b/.test(&#8220;in ter est&#8221;) //true /a<em>/ 找出 0 個或是 1 個以上的 a；而 /a*/ 找出 &#8216;a</em>&#8216; 這個字串 /aaaa*/g.test(&#8220;caaady&#8221;) //true /a*/.test(&#8220;caaady&#8221;) //false &#8216;\&#8217; 也能使自身表現出來，表現 &#8216;\&#8217; ，必須以 &#8216;\&#8217; 表達。 /[\]/.test(&#8220;>\&lt;&#8220;) //true</li>



<li>^ 匹配輸入的開頭，如果 multiline flag 被設為 true，則會匹配換行字元後。例如：/^A/ 不會匹配「an A」的 A，但會匹配「An E」中的 A。「^」出現在字元集模式的字首中有不同的意思，詳見補字元集。</li>



<li>$ 匹配輸入的結尾，如果 multiline flag 被設為 true，則會匹配換行字元。例如：/t$/ 不會匹配「eater」中的 t，卻會匹配「eat」中的 t。</li>



<li>* 匹配前一字元 0 至多次。 下面舉例要求基本 &#8216;aaaa&#8217; ，&#8217;a<em>&#8216; 後面有 0 個或多個 a 的意思 /aaaaa</em>/g.test(&#8220;caaady&#8221;) //false 例如：/bo*/ 匹配「A ghost booooed」中的 boooo、「A bird warbled」中的 b，但在「A goat grunted」中不會匹配任何字串。</li>



<li>+ 匹配前一字元 1 至多次，等同於 {1,}。例如：/a+/ 匹配「candy」中的 a，以及所有「caaaaaaandy」中的 a。</li>



<li>? 匹配前一字元 0 至 1 次，等同於 {0,1}。例如：/e?le?/ 匹配「angel」中的 el、「angle」中的 le、以及「oslo」中的 l。如果是使用在 *、+、? 或 {} 等 quantifier 之後，將會使這些 quantifier non-greedy（也就是儘可能匹配最少的字元），與此相對的是 greedy（匹配儘可能多的字元）。例如：在「123abc」中應用 /\d+/ 可匹配「123」，但使用 /\d+?/ 在相同字串上只能匹配「1」。 Also used in lookahead assertions, as described in the x(?=y) and x(?!y) entries of this table.<br>. （小數點）匹配除了換行符號之外的單一字元。例如：/.n/ 匹配「nay, an apple is on the tree」中的 an 和 on，但在「nay」中沒有匹配。</li>



<li>x|y 符合「x」或「y」。舉例來說，/green|red/ 的話，會匹配 &#8220;green apple&#8221; 中的 &#8220;green&#8221; 以及 &#8220;red apple.&#8221; 的 &#8220;red&#8221; 。</li>



<li>{n} 規定符號確切發生的次數，n 為正整數例如：/a{2}/無法在 &#8220;candy&#8221; 找到、但 &#8220;caandy&#8221; 行；若字串擁有 2 個以上 &#8220;caaandy&#8221; 還是只會認前面 2 個。</li>



<li>{n,m} 搜尋條件：n 為至少、m 為至多，其 n、m 皆為正整數。若把 m 設定為 0，則為 Invalid regular expression。例如：/a{1,3}/無法在 &#8220;cndy&#8221; 匹配到；而在 &#8220;candy&#8221; 中的第 1 個&#8221;a&#8221;符合；在 &#8220;caaaaaaandy&#8221; 中的前 3 個 &#8220;aaa&#8221; 符合，雖然此串有許多 a，但只認前面 3 個。</li>



<li>[xyz] 字元的集合。此格式會匹配中括號內所有字元, including escape sequences。特殊字元，例如點（.） 和米字號（*），在字元集合中不具特殊意義，所以不需轉換。若要設一個字元範圍的集合，可以使用橫線 &#8220;-&#8221; ，如下例所示： [a-d] 等同於 [abcd]。會匹配 &#8220;brisket&#8221; 的 &#8220;b&#8221; 、&#8221;city&#8221; 的 &#8216;c&#8217; ……等。 而/[a-z.]+/ 和 /[\w.]+/ 均可匹配字串 &#8220;test.i.ng&#8221; 。</li>
</ul>



<p></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>範例3 some：</p>



<p>You can create an array of keywords and use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some"><code>some</code></a> to check if at least one of them exists in the string.</p>



<pre class="wp-block-code"><code>const caption = "I love dogs";
const animals = &#91;"dog", "fish", "bird", "cat"];
const exists = animals.some(animal =&gt; caption.includes(animal))

if (exists) {
  console.log("Yes");
  // notify 
}</code></pre>



<p></p>



<h2 class="wp-block-heading">資料來源</h2>



<p>Javascript: Check for an array of keywords match in a string<br><a href="https://stackoverflow.com/questions/54900214/javascript-check-for-an-array-of-keywords-match-in-a-string">https://stackoverflow.com/questions/54900214/javascript-check-for-an-array-of-keywords-match-in-a-string</a></p>



<p>How to check if contains all keywords in any order of string? RegExp Javascript<br><a href="https://stackoverflow.com/questions/41748030/how-to-check-if-contains-all-keywords-in-any-order-of-string-regexp-javascript">https://stackoverflow.com/questions/41748030/how-to-check-if-contains-all-keywords-in-any-order-of-string-regexp-javascript</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/11/javascript-check-for-an-array-of-keywords-match-in-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>javascript generate the opposite color</title>
		<link>https://stackoverflow.max-everyday.com/2024/11/javascript-generate-the-opposite-color/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/11/javascript-generate-the-opposite-color/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 01 Nov 2024 10:18:08 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=6000</guid>

					<description><![CDATA[要如何取得某顏色的反差色？ 使用太多顏色太花俏，...]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="379" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/s82pU-1024x379.png" alt="" class="wp-image-6001" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/s82pU-1024x379.png 1024w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/s82pU-600x222.png 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/s82pU-768x284.png 768w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/s82pU.png 1206w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>要如何取得某顏色的反差色？</p>



<p>使用太多顏色太花俏，使用二極化黑與白，效果會更好，上圖是進階版，指定 bw=true。</p>



<p>解法：How can I generate the opposite color according to current color?<br><a href="https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color">https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color</a></p>



<p>This is how I&#8217;d do it:</p>



<ol class="wp-block-list">
<li>Convert HEX to RGB</li>



<li>Invert the R,G and B components</li>



<li>Convert each component back to HEX</li>



<li>Pad each component with zeros and output.</li>
</ol>



<pre class="wp-block-code"><code>function invertColor(hex) {
    if (hex.indexOf('#') === 0) {
        hex = hex.slice(1);
    }
    // convert 3-digit hex to 6-digits.
    if (hex.length === 3) {
        hex = hex&#91;0] + hex&#91;0] + hex&#91;1] + hex&#91;1] + hex&#91;2] + hex&#91;2];
    }
    if (hex.length !== 6) {
        throw new Error('Invalid HEX color.');
    }
    // invert color components
    var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
        g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
        b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
    // pad each with zeros and return
    return '#' + padZero(r) + padZero(g) + padZero(b);
}

function padZero(str, len) {
    len = len || 2;
    var zeros = new Array(len).join('0');
    return (zeros + str).slice(-len);
}
</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p><strong>Advanced Version:</strong></p>



<p>This has a&nbsp;<code>bw</code>&nbsp;option that will decide whether to invert to black or white; so you&#8217;ll get more contrast which is generally better for the human eye.</p>



<pre class="wp-block-code"><code>function invertColor(hex, bw) {
    if (hex.indexOf('#') === 0) {
        hex = hex.slice(1);
    }
    // convert 3-digit hex to 6-digits.
    if (hex.length === 3) {
        hex = hex&#91;0] + hex&#91;0] + hex&#91;1] + hex&#91;1] + hex&#91;2] + hex&#91;2];
    }
    if (hex.length !== 6) {
        throw new Error('Invalid HEX color.');
    }
    var r = parseInt(hex.slice(0, 2), 16),
        g = parseInt(hex.slice(2, 4), 16),
        b = parseInt(hex.slice(4, 6), 16);
    if (bw) {
        // https://stackoverflow.com/a/3943023/112731
        return (r * 0.299 + g * 0.587 + b * 0.114) &gt; 186
            ? '#000000'
            : '#FFFFFF';
    }
    // invert color components
    r = (255 - r).toString(16);
    g = (255 - g).toString(16);
    b = (255 - b).toString(16);
    // pad each with zeros and return
    return "#" + padZero(r) + padZero(g) + padZero(b);
}</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>實作的結果1：只加入陰影</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="700" height="500" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-2.png?v=1730713671" alt="" class="wp-image-6003" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-2.png?v=1730713671 700w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-2-600x429.png?v=1730713671 600w" sizes="(max-width: 700px) 100vw, 700px" /></figure>
</div>


<p></p>



<p>實作的結果2：依舊填入的顏色判斷最佳前景色, 並加入陰影</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="700" height="500" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-3.png?v=1730713726" alt="" class="wp-image-6005" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-3.png?v=1730713726 700w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-3-600x429.png?v=1730713726 600w" sizes="(max-width: 700px) 100vw, 700px" /></figure>
</div>


<p></p>



<p>實作的結果3：依舊填入的顏色判斷最佳前景色, 效果就滿好的了。</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="700" height="500" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-4.png?v=1730713807" alt="" class="wp-image-6006" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-4.png?v=1730713807 700w, https://stackoverflow.max-everyday.com/wp-content/uploads/2024/11/Pie_chart-4-600x429.png?v=1730713807 600w" sizes="(max-width: 700px) 100vw, 700px" /></figure>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/11/javascript-generate-the-opposite-color/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Select Element That Does Not have Specific Class</title>
		<link>https://stackoverflow.max-everyday.com/2024/10/select-element-that-does-not-have-specific-class/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/10/select-element-that-does-not-have-specific-class/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 30 Oct 2024 04:36:48 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5981</guid>

					<description><![CDATA[如何選取某個 element 而且不包含特定 c...]]></description>
										<content:encoded><![CDATA[
<p>如何選取某個 element 而且不包含特定 class name?</p>



<p>解法：</p>



<h2 class="wp-block-heading">Simple example: excluding by class</h2>



<p><code>div:not(.class)</code></p>



<p>Would select all&nbsp;<code>div</code>&nbsp;elements without the class&nbsp;<code>.class</code></p>



<pre class="wp-block-code"><code>div:not(.class) {
  color: red;
}</code></pre>



<pre class="wp-block-code"><code>&lt;div&gt;Make me red!&lt;/div&gt;
&lt;div class="class"&gt;...but not me...&lt;/div&gt;</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Complex example: excluding by type / hierarchy</h2>



<p><code>:not(div) &gt; div</code></p>



<p>Would select all&nbsp;<code>div</code>&nbsp;elements which arent children of another&nbsp;<code>div</code></p>



<pre class="wp-block-code"><code>div {
  color: black
}
:not(div) &gt; div {
  color: red;
}</code></pre>



<pre class="wp-block-code"><code>&lt;div&gt;Make me red!&lt;/div&gt;
&lt;div&gt;
  &lt;div&gt;...but not me...&lt;/div&gt;
&lt;/div&gt;</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Complex example: chaining pseudo selectors</h2>



<p>With the notable exception of not being able to chain/nest&nbsp;<code>:not</code>&nbsp;selectors and pseudo elements, you can use in conjunction with other pseudo selectors.</p>



<pre class="wp-block-code"><code>div {
  color: black
}
:not(:nth-child(2)){
  color: red;
}</code></pre>



<pre class="wp-block-code"><code>&lt;div&gt;
  &lt;div&gt;Make me red!&lt;/div&gt;
  &lt;div&gt;...but not me...&lt;/div&gt;
&lt;/div&gt;</code></pre>



<p></p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">資料來源</h2>



<ul class="wp-block-list">
<li>How to Select Element That Does Not have Specific Class<br><a href="https://stackoverflow.com/questions/21975881/how-to-select-element-that-does-not-have-specific-class">https://stackoverflow.com/questions/21975881/how-to-select-element-that-does-not-have-specific-class</a></li>



<li>Can I write a CSS selector selecting elements NOT having a certain class or attribute?<br><a href="https://stackoverflow.com/questions/9110300/can-i-write-a-css-selector-selecting-elements-not-having-a-certain-class-or-attr">https://stackoverflow.com/questions/9110300/can-i-write-a-css-selector-selecting-elements-not-having-a-certain-class-or-attr</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/10/select-element-that-does-not-have-specific-class/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>javascript playsound chrome extension Manifest V3</title>
		<link>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Tue, 29 Oct 2024 10:26:41 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[chrome]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5977</guid>

					<description><![CDATA[如何在 chrome extension 裡播放...]]></description>
										<content:encoded><![CDATA[
<p> 如何在 chrome extension 裡播放音樂：</p>



<ul class="wp-block-list">
<li>Chrome Extension V3 offscreen audio not working due to &#8220;Receiving end does not exist.&#8221;<br><a href="https://stackoverflow.com/questions/78110557/chrome-extension-v3-offscreen-audio-not-working-due-to-receiving-end-does-not-e">https://stackoverflow.com/questions/78110557/chrome-extension-v3-offscreen-audio-not-working-due-to-receiving-end-does-not-e</a><br>附註：上面網址裡附的範例，有 typo 錯誤，<code>message</code> 應該改為 <code>msg</code> </li>



<li>Play audio from background script in chrome extention manifest v3<br><a href="https://stackoverflow.com/questions/67437180/play-audio-from-background-script-in-chrome-extention-manifest-v3">https://stackoverflow.com/questions/67437180/play-audio-from-background-script-in-chrome-extention-manifest-v3</a></li>
</ul>



<p></p>



<p>程式碼：</p>



<p><code>manifest.json</code></p>



<pre class="wp-block-code"><code>...
"permissions": &#91;"offscreen"]
...
</code></pre>



<p><code>background.js</code></p>



<pre class="wp-block-code"><code>/**
 * Plays audio files from extension service workers
 * @param {string} source - path of the audio file
 * @param {number} volume - volume of the playback
 */
async function playSound(source = 'default.wav', volume = 1) {
    await createOffscreen();
    await chrome.runtime.sendMessage({ play: { source, volume } });
}

// Create the offscreen document if it doesn't already exist
async function createOffscreen() {
    if (await chrome.offscreen.hasDocument()) return;
    await chrome.offscreen.createDocument({
        url: 'offscreen.html',
        reasons: &#91;'AUDIO_PLAYBACK'],
        justification: 'testing' // details for using the API
    });
}
</code></pre>



<p><code>offscreen.html</code></p>



<pre class="wp-block-code"><code>&lt;script src="offscreen.js"&gt;&lt;/script&gt;
</code></pre>



<p><code>offscreen.js</code></p>



<pre class="wp-block-code"><code>// Listen for messages from the extension
chrome.runtime.onMessage.addListener(msg =&gt; {
    if ('play' in msg) playAudio(msg.play);
});

// Play sound with access to DOM APIs
function playAudio({ source, volume }) {
    const audio = new Audio(source);
    audio.volume = volume;
    audio.play();
}</code></pre>



<p></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/10/javascript-playsound-chrome-extension-manifest-v3/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
